quotation

AJAX, Asynchronous Javascript And XML, is a web development technique for creating interactive web applications.

AJAX is a technique for creating fast, dynamic web pages. It can make the developers only to get the data from the server (rather than images, HTML documents and other resources), the resources of the Internet transmission become unprecedented lightweight and pure, it inspired the majority of developers creativity, make all kinds of powerful web sites, and Internet applications have mushroomed in general, continuously to surprise people.

What is AJAX

Ajax is a Web development technique that asynchronously requests data, which can help improve user experience and page performance. Simply put, Ajax loads background data through asynchronous requests and renders it on a web page without the need to refresh the page. Common application scenarios include form verification whether login is successful, Baidu search drop-down box prompt and express tracking number query, etc.

Ajax is designed to improve the user experience and reduce the amount of data transferred over the network. Also, because AJAX requests fetch data rather than HTML documents, it saves network bandwidth and makes the web surfing experience smoother for Internet users.

What is the principle of AJAX

Ajax adds an intermediate layer between the user and the server, making user actions and server responses asynchronous. Not all user requests are submitted to the server. Some data validation and data processing are left to the Ajax engine itself. Only when new data needs to be read from the server can the Ajax engine submit requests to the server.

Ajax works simply by sending an asynchronous request to the server via an XmlHttpRequest object, retrieving data from the server, and then using JavaScript to manipulate the DOM to update the page. One of the most critical steps is getting the request data from the server. To understand this process and how it works, you must understand XMLHttpRequest.

XMLHttpRequest is the core mechanism of Ajax. It was first introduced in IE5 and is a technology that supports asynchronous requests. In simple terms, JavaScript can make requests to the server and process responses in a timely manner without blocking the user. Achieve no refresh effect.

The use of AJAX

1. Create Ajax core objectsXMLHttpRequest(Remember to consider compatibility)

let xhr = null;
if (window.`XMLHttpRequest`) {// Compatible with IE7+, Firefox, Chrome, Opera, Safari
	xhr = new `XMLHttpRequest`(a); }else {// Compatible with IE6 and IE5
	xhr = new ActiveXObject("Microsoft.XMLHTTP");  
} 
Copy the code

2. Send a request to the server

xhr.open(method, url, async);  
send(string);// 'POST' requests only use string arguments, otherwise no arguments.
Copy the code
  • method: Type of request;GETPOST
  • url: Location of the file on the server
  • async: true (asynchronous) or false (synchronous)Note:POSTThe request must set the formatting content of the request header
xhr.open("`POST`"."test.html".true);  
xhr.setRequestHeader("Content-type"."application/x-www-form-urlencoded");  
xhr.send("fname=Henry&lname=Ford");  // 'POST' request parameters are placed in send, i.e. the request body
Copy the code

An example of an Ajax operation implemented by a Promise object:

const getJSON = function(url) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState ! = =4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText)); }};const client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept"."application/json");
    client.send();
  });
  return promise;
};

getJSON("/posts.json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('Wrong', error);
});
Copy the code

3. Server response processing (distinguish synchronous and asynchronous cases)

ResponseText gets the response data as a string. ResponseXML gets the response data in XML form.

Synchronous processing
xhr.open("`GET`"."info.txt".false);  
xhr.send();  
document.`GET`ElementById("myDiv").innerHTML = xhr.responseText; // Get data to display directly on the page
Copy the code
Asynchronous processing (recommended)

It is relatively complex to handle in a request state change event.

xhr.onreadystatechange = function() { 
	if (xhr.readyState == 4 && xhr.status == 200) {document.`GET`ElementById("myDiv").innerHTML = xhr.responseText; }}Copy the code
What is thereadyState?

ReadyState is an attribute of the XMLHttpRequest object that identifies the current state of the XMLHttpRequest object. ReadyState has five status values ranging from 0 to 4, each representing a different meaning:

  • 0: uninitialized – the.open() method has not been called;
  • 1: start – the.open() method has been called, but the.send() method has not been called;
  • 2: send – The.send() method has been called, but no response has been received;
  • 3: Receive – Some response data has been received.
  • 4: done – All response data has been received and is ready for use on the client.
What is thestatus?

The HTTP status code consists of three decimal digits. The first decimal digit defines the type of the status code, and the second two digits do not classify. HTTP status codes are classified into five types:

  • 1XX (temporary response) : Status code that represents a temporary response and requires the requester to continue performing the operation.
  • 2xx (success) : Indicates that the request status code is successfully processed.
  • 3XX (redirect) : Indicates that further action is required to complete the request. Typically, these status codes are used for redirects.
  • 4XX (Request error) : These status codes indicate that the request may be in error, preventing the server from processing it.
  • 5XX (server errors) : These status codes indicate that an internal error occurred while the server was trying to process the request. These errors may be server errors rather than request errors.
Common status codes

There are 40 types of HTTP status codes recorded in RFC2616 alone, and more than 60 types if WebDAV (RFC4918, 5842) and additional HTTP status codes (RFC6585) are added. Next, let’s take a look at some of these representative status codes.

  • 200Indicates that the request from the client is processed on the server.
  • 204Indicates that the request was processed successfully, but no resources were returned.
  • 301Represents a permanent redirect. This status code indicates that the requested resource has been assigned a new URI and that the URI to which the resource now refers should be used later.
  • 302Represents a temporary redirect.
  • 304Indicates when a client sends a conditional requestGETMethod, including if-matched,if-modified-since,if-none-match,if-range,if-unmodified-since any header) the server allows the request to access resources, but when the request condition is not met, Return 304Modified (the server resource has not changed and can use the client’s cache without expiration)
  • 400Syntax errors exist in the request packet. When an error occurs, you need to modify the content of the request and send the request again.
  • 401Indicates that the request is Unauthorized and requires user authentication
  • 403Indicates that access to the requested resource was denied by the server
  • 404The requested resource could not be found on the server. In addition, it can be used when the server rejects the request without giving a reason.
  • 500Indicates an error occurred on the server side while executing the request. It could also be a Web application bug or some temporary glitch.
  • 503Indicates that the server is temporarily overloaded or is down for maintenance and cannot process requests at this time.

4. GETandPOSTRequest data distinction

  1. GETIs harmless when the browser falls back, whilePOSTThe request will be submitted again.
  2. GETThe resulting URL address can be bookmarked, whilePOSTCan’t.
  3. GETRequests will be actively cached by the browser, whilePOSTNo, unless you set it manually.
  4. GETRequests can only be URL-encoded, whilePOSTSupports multiple encoding modes.
  5. GETRequest parameters are fully preserved in browser history, whilePOSTParameters in are not retained.
  6. GETRequest parameters passed in the URL are limited in length, whilePOSTIt has.
  7. For the data type of the parameter,GETOnly ASCII characters are accepted, andPOSTThere is no limit.
  8. GETthanPOSTLess secure, because parameters are directly exposed to the URL and therefore cannot be used to pass sensitive information.
  9. GETParameters are passed through the URL,POSTPut it in the Request body.

GET and POST scenarios: POST is recommended if any of the following scenarios are met:

  • The result of the request has persistent side effects, such as adding new rows to the database.
  • If useGETMethod, the data collected on the form may make the URL too long.
  • The data to be transmitted is not 7-bit ASCII.

The GET method is recommended if any of the following conditions occur:

  • The request is to find the resource, and the HTML form data is used only to aid the search.
  • Request results have no lasting side effects.
  • The total length of the collected data and input field names in the HTML form cannot exceed 1024 characters.

4. Common AJAX interview questions

What is AJAX? What does AJAX do?

See this article for details =>

How many steps does a native JavaScript AJAX request take? What are they?
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Type of content encoding when sending messages to the server
xhr.setRequestHeader("Content-type"."application/x-www-form-urlencoded"); 
// Accept server response data
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && (xhr.status == 200) { 
		// let data = xhr.responseText;  }};// Specify the type of request, URL, and whether the request is processed asynchronously.
xhr.open('GET',url,true);
// Send the request
xhr.send(null);  
Copy the code
JSON string and JSON object conversion
// String to object
JSON.parse(json)
eval('(' + jsonstr + ') ')   

// Object to string
JSON.stringify(json)
Copy the code
How many AJAX requests? What are their strengths and weaknesses?

See this article for details =>

What are the common HTTP status codes?

See this article for details =>

What causes cross-domain (what is the same origin policy)?

The same origin policy is a security function of the browser. Client scripts from different sources cannot read or write resources from each other without explicit authorization. So js scripts under xyz.com that use Ajax to read abc.com files will be rejected.

The same origin policy restricts how documents or scripts loaded from the same source can interact with resources from another source. This is an important security mechanism for isolating potentially malicious files.

Here’s an example:

Conditions not restricted by the same Origin policy:

  1. Links, redirects, and form submissions on pages are not restricted by the same origin policy.
  2. Cross-domain resource introductions are possible. But JS cannot read or write loaded content. As embedded in a page,,, etc.
    What are the cross-domain solutions?
    • JSONP can only solve the GET cross-domain (ask most) principle: ** Dynamically create a script tag. SRC attributes using script tags are not restricted by the same origin policy. All SRC and href attributes are not subject to the same origin policy. Third party server data content can be requested. Step: 1. Create a script tag. 2. Interface parameter, must have a custom function name otherwise background cannot return data. 4. Define function names to receive background data

      // create a script tag let script = document.createElement("script"); / / script set the SRC attribute of the interface address And take a callback callback function name script. The SRC = "http://127.0.0.1:8888/index.php? callback=jsonpCallback"; / / is inserted into the page document. The head. The appendChild (script). Function jsonpCallback(data){// jsonpCallback(data){// jsonpCallback(jsonpCallback){// jsonpCallback(jsonpCallback){// jsonpCallback(jsonpCallback){// jsonpCallback(jsonpCallback){ } ` ` `Copy the code
    • CORS: Cross-domain resource sharing Principle: After the SERVER sets the ACCESS-Control-allow-originHTTP response header, the browser allows cross-domain request restrictions. The browser must support HTML5, POST, PUT, and other methods, which are compatible with Internet Explorer 9

      Access-Control-Allow-Origin: *              // Allow all domain names to access, or
      Access-Control-Allow-Origin: http://a.com // All domain names only
      Copy the code
    • Document.domain principle: The same master domain name under different subdomain pages, you can set the document.domain to let them co-domain restrictions: co-domain document provides the interoperation between pages, need to load iframe page

      // URL http://a.com/foo
      var ifr = document.createElement('iframe');
      ifr.src = 'http://b.a.com/bar'; 
      ifr.onload = function(){
          var ifrdoc = ifr.contentDocument || ifr.contentWindow.document;
          ifrdoc.getElementsById("foo").innerHTML);
      };
      ifr.style.display = 'none';
      document.body.appendChild(ifr);
      Copy the code
    • ES5 postMessage The postMessage() method in ES5 allows scripts from different sources to communicate asynchronously in a limited manner, enabling cross-text file, multi-window, cross-domain messaging. Grammar:

      postMessage(data,origin)
      Copy the code
    • Use Apache as a forwarding (reverse proxy) to make cross-domain co-domain

    Five, the conclusion

    In fact, network requests via XMLHttpRequest or a wrapped framework are a bit old and messy to configure and invoke. Fetch, which has just emerged in recent years, provides a better alternative. It not only provides a simple and logical way to Fetch resources asynchronously across the network, And it can be easily used by other technologies.


    Recommended reading:

    [Topic: the Way to Advanced JavaScript]

    Implementation of various source code in JavaScript

    Function physics of JavaScript

    ES6 tail calls and tail recursion

    Reference:

    How Ajax works is enough in one article · Issue #45 · Ljianshu

    Ajax profile

    Never learn AJAX again! (a) AJAX overview

    HTTP rookie tutorial Ajax MDN document Ajax common interview questions – axe Rabbit – blog park


    I’m Cloudy, now living in Shanghai, a young front-end siege lion, love research, love technology, love to share. Personal notes, not easy to organize, thanks for your attention, reading, like and favorites. The article has any problem welcome to point out, also welcome to communicate with all kinds of front-end problems!