js basics ajax and cors


DOM is the interface for JavaScript to operate web pages, and its full name is "Document Object Model". Its function is to turn the web page into a JavaScript object, so that you can use scripts for various operations (such as adding and deleting content).


The smallest component of DOM is called node. The tree structure of a document (DOM tree) is composed of various types of nodes. Each node can be regarded as a leaf of the document tree.

There are seven types of nodes:

  • Document: the top-level node of the entire document tree

  • DocumentType: doctype tag (such as <! doctype HTML >)

  • Element: various HTML tags of web pages (such as < body >, < a >, etc.)

  • Attr: attribute of web page element (such as class="right")

  • Text: text between or contained in labels

  • Comment: comment

  • DocumentFragment: a fragment of a document

node interface properties

The nodeType attribute values and corresponding constants of different nodes are as follows:

  • document node: 9, corresponding to constant node document_ NODE
  • element: 1, corresponding to constant node element_ NODE
  • Attribute node (attr): 2, corresponding to constant node ATTRIBUTE_ NODE
  • text node: 3, corresponding to constant node text_ NODE
  • Document fragment node: 11, corresponding to constant node DOCUMENT_ FRAGMENT_ NODE
  • Document type node: 10, corresponding to constant node DOCUMENT_ TYPE_ NODE
  • Comment node: 8, corresponding to constant node COMMENT_ NODE

When determining the node type, it is a common method to use the nodeType attribute.

2.Element node

The nodeType attribute of element nodes is 1

var p = document.querySelector('p');
console.info(p.nodeName)    // "p"
console.info(p.nodeType)    // 1 (the attribute of the element node is 1)


Property returns the id attribute of the specified element, which is readable and writable

// The HTML code is < p id = "foo" >
var p = document.querySelector('p');
console.info(p.id)   // The value of "foo" ID attribute is case sensitive. The browser can correctly identify the ID attributes of < p id = "foo" > and < p id = "foo" > elements


Element. The tagName property returns the upper case label name of the specified element, equal to the value of the nodeName property.

// The HTML code is < span id = "myspan" > hello</span>
var span = document.getElementById('myspan');
console.info(span.id)       //"myspan"
console.info(span.tagName)  // "SPAN"


Element. The attributes attribute returns an array like object whose members are all attribute nodes of the current element node

js is similar to an array pair: a normal array without the length attribute. We are similar to the array object, which implements the array method, but it has one more attribute than the array, that is, length

var p = document.querySelector('p');
var attrs = p.attributes;
for (var i = attrs.length - 1; i >= 0; i--) {
  console.log(attrs[i].name + '->' + attrs[i].value);


Element. The innerHTML attribute returns a string equal to all the HTML code contained in the element. This attribute is readable and writable. It is often used to set the content of a node. It can rewrite the contents of all element nodes, including < HTML > and < body > elements.

If the innerHTML attribute is set to null, it will delete all the nodes it contains.

el.innerHTML = '';     take el The node becomes an empty node, el All the original nodes are deleted

Note that when reading the attribute value, if the text node contains &, less than sign (<) and greater than sign (>), the innerHTML attribute will convert them to entity form & amp& lt;,& gt;. If you want to get the original text, it is recommended to use element Textcontent property.

<p id="p" name="p1" class="p2">5>3</p>
var p=document.getElementById('p')
console.info(p.innerHTML);      //5&gt;3

If the text contains a < script > tag, a script node can be generated, but the inserted code will not be executed.

var name = "<script>alert('haha')</script>";
el.innerHTML = name;
var el=document.getElementById('p')
var name="<svg οnlοad=alert(1)>";
el.textContent=name;     //<svg οnlοad=alert(1)>

In the above code, the alert method is executed. Therefore, for security reasons, if you insert text, you'd better use the textContent attribute instead of innerHTML.


Element. The getelementsbyclassname method returns an HTMLCollection instance whose members are all child element nodes of the current element node with the specified class. This method is similar to document The getelementsbyclassname method is used similarly, except that the search scope is not the entire document, but the current element node.

var element = document.getElementById('example');      Single element
var matches = element.getElementsByClassName('foo');   array

Element.getElementsByTagName() (element name)

Element. The getElementsByTagName () method returns an HTMLCollection instance whose members are all child element nodes of the current node that match the specified tag name. This method is similar to document The getelementsbyclassname () method is used similarly, except that the search scope is not the entire document, but the current element node.

Note that the parameters of this method are case insensitive because HTML tag names are also case insensitive.

js is strictly case sensitive


Element. The focus method is used to shift the focus of the current page to the specified element.

<input type="text" id="demo">

Focus directly without clicking


<p id="demo" onclick="alert(1)">aaa</p>

In the above code, click aaa and a pop-up window will appear



The insertBefore method is used to insert a node into a specified location inside the parent node.

var insertedNode = parentNode.insertBefore(newNode,referenceNode);

The insertBefore method accepts two parameters. The first parameter is the node newNode to be inserted, and the second parameter is a child node referenceNode within the parent node parentNode. newNode will be inserted in front of the child node referenceNode. The return value is the inserted new node newNode.

 var p =document.createElement('p');

In the above code, create a < p > node and insert it in document body. In front of firstchild, that is, it becomes document The first child node of the body.

If the second parameter of Hugo is null, the new node will be inserted in the last position inside the current node, that is, it will become the last child node. Then the running sequence of the above code is a b ppp


The replaceChild method is used to replace a child node of the current node with a new node.

var replacedNode = parentNode.replaceChild(newChild, oldChild);

In the above code, replace the old node with the new node

var div = document.getElementById('example'); 
var span = document.createElement('span');
span.textContent = 'Hello World!'; div.parentNode.replaceChild(span,div);   hello world Replace div Content in

3. Mouse events

Mobile event

  • mousemove: triggered when the mouse moves inside a node. This event is triggered continuously when the mouse continues to move. In order to avoid performance problems, it is recommended to limit the listening function of this event. For example, it can only be run once in a period of time.
  • mouseenter: triggered when the mouse enters a node. Entering a child node will not trigger this event
  • mouseover: triggered when the mouse enters a node. Entering a child node will trigger this event again (recommended)

Mouseover events and mouseenter events are triggered when the mouse enters a node. The difference between the two is that the mouseenter event is triggered only once, while as long as the mouse moves inside the node, the mouseover event will be triggered multiple times on the child node.

   <li>item 1</li>
   <li>item 2</li>
   <li>item 3</li>

var ul = document.querySelector('ul');
// After entering the ul node, the mouseenter event will be triggered only once
// In the future, this event will not be triggered as long as the mouse moves within the node
// event.target is the ul node
ul.addEventListener('mouseenter', function (event) {
event.target.style.color = 'purple';
setTimeout(function () {
event.target.style.color = '';   The first parameter can be either a string or a function
 }, 500);       Second parameter,How many seconds is the delay in execution
}, false);       Listening for events false
// After entering the ul node, the mouseover event will be triggered multiple times as long as it moves on the child node
// event.target is the li node
ul.addEventListener('mouseover', function (event) {
event.target.style.color = 'orange';
setTimeout(function () {
event.target.style.color = '';
  }, 500);
}, false);

4.XMLHttpRequest object

$_ request can receive three parameter transfer methods: get, post and request

XMLHttpRequest itself is a constructor that can generate an instance using the new command. It has no parameters.

var xhr = new XMLHttpRequest();

Note that AJAX can only send HTTP requests to the same source web address (protocol, domain name and port are the same). If a cross domain request is sent, an error will be reported

The following is a complete example of the simple usage of the XMLHttpRequest object

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
  // When the communication is successful, the status value is 4
  if (xhr.readyState === 4){    Standard status, 4 when successful
    if (xhr.status === 200){
    } else {

xhr.onerror = function (e) {

xhr.open('GET', '/endpoint', true);   GET Delivery mode  /endpoint Path passed   ture See if it's asynchronous
xhr.send(null);   send Pass what value to the past
 In the code above, send()The parameters are null,Indicates that the request is sent without a data body. If you are sending POST Request, you need to specify the data body here.

Once you get the data returned by the server, AJAX will not refresh the whole web page, but only update the relevant parts of the web page, so as not to interrupt what the user is doing.


  • "" (empty string): equivalent to text, indicating that the server returns text data.
  • "ArrayBuffer": an ArrayBuffer object that represents a binary array returned by the server.
  • "Blob": blob object, indicating that the server returns binary objects.
  • "Document": a document object, indicating that the server returns a document object.
  • "JSON": JSON object.
  • "text": String

XMLHttpRequest.response (read only)

XMLHttpRequest.responseType (writable, after calling the open() method and before the send() method) -- when the responseType is set to null (equivalent to the default value of text)

blob type is suitable for reading binary data, such as picture files

var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'blob';   Picture in front, use blod(Set binary return value)

If this property is set to ArrayBuffer, binary data can be processed as an array

Event listening properties

The XMLHttpRequest object can specify a listener function for the following events.

  • XMLHttpRequest.onloadstart: the listener function for the loadstart event (HTTP request issuance)
  • XMLHttpRequest.onprogress: listener function for progress event (sending and loading data)
  • XMLHttpRequest.onabort: listener function for abort event (request abort, for example, the user called abort() method)
  • XMLHttpRequest.onerror: listener function for error event (request failure)
  • XMLHttpRequest.onload: the listening function for the load event (request completed successfully)
  • XMLHttpRequest.ontimeout: the listening function for the timeout event (the time limit specified by the user has exceeded, and the request has not been completed)
  • XMLHttpRequest. On loadend: the listener function for the load event (request completion, regardless of success or failure)


XMLHttpRequest. The withcredentials property is a Boolean value indicating whether user information (such as cookies and authenticated HTTP header information) will be included in the request when a cross domain request is made. The default value is false, that is, to example example.com will not be sent when making a cross domain request Com Cookie Set on this computer (if any).

If you need to send cookies for cross domain AJAX requests, you need to set the withCredentials property to true (cookies and withCredentials exist at the same time). This property is not required for homologous requests.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;

For this property to take effect, the server must explicitly return the header access control allow credentials.

Access-Control-Allow-Credentials: true

5.cors communication

CORS is a W3C standard, whose full name is "cross origin resource sharing". It allows browsers to issue XMLHttpRequest requests to cross domain servers, thus overcoming the limitation that AJAX can only be used from the same source.

Simple request

(1) The request method is one of the following three methods.

  • HEAD
  • GET
  • POST
    (2) The header information of HTTP does not exceed the following fields.
  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content type: limited to three values: application/x-www-form-urlencoded, multipart / form data, and text/plain

Basic process

For simple requests, the browser sends CORS requests directly. Specifically, add an Origin field to the header information.

GET /cors HTTP/1.1
Origin: http://api.bob.com is a simple request, which automatically adds an origin field to the header information
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

The origin field is used to indicate which domain (protocol + domain name + port) the request comes from. Based on this value, the server decides whether to agree to the request.
If the domain name specified by Origin is within the license range, several header information fields will be added to the response returned by the server.

Access-Control-Allow-Origin: http://api.bob.com  
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8
Access control allow origin (important)

This field is required. Its value is either the value of the Origin field at the time of the request, or a *, indicating that the request for any domain name is accepted.


This field is optional. Its value is a Boolean value indicating whether cookies are allowed to be sent. By default, cookies are not included in CORS requests. If it is set to true, it means that the server has explicit permission. The browser can include cookies in the request and send them to the server together. This value can only be set to true. If the server does not want the browser to send cookies, it can not send this field.


This field is optional. When CORS requests, the getResponseHeader() method of XMLHttpRequest object can only get six basic fields returned by the server: cache control, content language, content type, Expires, last modified and Pragma. If you want to get other fields, you must specify them in access control expose headers. The above example specifies that getResponseHeader('FooBar ') can return the value of the FooBar field.

var xhr=new XMLHttpRequest();{
var url='';
 echo 'wang pei ting';

CORS is used for the same purpose as JSONP, but it is more powerful than JSONP. JSONP only supports GET requests, and CORS supports all types of HTTP requests. The advantages of JSONP are that it supports old-fashioned browsers and can request data from websites that do not support CORS.

Keywords: Javascript Front-end html security

Added by cqinzx on Fri, 14 Jan 2022 17:19:05 +0200