Ajax usage principle Cross-domain JSONP

1. What is Ajax?

Ajax, also called asynchronous js or xml, is a communication technology between the browser and the server. It can send HTTP requests to the server to obtain data without refreshing the web page.

2. Advantages and disadvantages of using Ajax

Advantages: Requesting data without refreshing the page, allowing users to partially update content based on events

Disadvantages: no history, no way to go back; there are crossover issues; not SEO friendly

3. Same origin strategy

In layman’s terms, it refers to the protocol followed by the browser and server. The port number and domain name must be the same, otherwise cross-domain problems will occur. Ajax accepts the same-origin policy by default.

4.What is HTTP protocol

The HTTP protocol, also called the Hypertext Transfer Protocol, stipulates the rules for communication between the browser and the World Wide Web, which includes request messages and response messages.

The request message contains: request line, request header, blank line, request body

Request line: request type, url, protocol version, etc.

Request headers: host, cookie, content-type, user-agent, etc.

Request body: GET request does not have a request body, and POST request can carry the request body.

The response message contains: response line, response header, blank line, response body

Response line: protocol version, status code, status code string

Response header: description of response content, content format, length, etc.

Response body: The content of the server’s response to the client

5. Use Ajax to send requests

step:

a Create XMLHttpRequest object

b Initialize the object and set the request method and request URL

c Send request

d Listen for events and process the returned data

readyState is an attribute of the XMLHttpRequest instance used to represent the status. It has five values: 0 (not initialized) 1 (open method has been called to initialize) 2 (send method has been called to send the request) 3 (the server has returned some data) 4 (the server has returned All data), you need to monitor the change of this attribute. When the attribute value is 4, the server has sent all the results to the user. At this time, the user will judge based on the status code of the response. Status codes greater than 200 and less than 300 are considered successful. , if the status code indicates success, the user can process the data at this time.

This is a simple GET request

//1. Create object
    const xhr = new XMLHttpRequest();
    //2. Initialization Set request method and url
    xhr.open("GET", "http://127.0.0.1/server");
    //3.Send
    xhr.send();
    //4. Event binding handles the results returned by the server
    //on listening event
    //The attributes of readystate xhr represent the status. There are 5 states.
    //0 Not initialized 1 Open has been called 2 Send method has been called 3 The server returns some results 4 The server returns all results
    //change event changed 4 times 0-1 1-2 2-3 3-4
    xhr.onreadystatechange = function () {
      //Process the results returned by the server when the status is 4
      if (xhr. readyState === 4) {
        //Judge the response status code. If the status code is greater than 200 and less than 300, it is considered successful.
        if (xhr.status >= 200 & amp; & amp; xhr.status <= 300) {
          //process result
          console.log(xhr.status); //Status code
          console.log(xhr.statusText); //Status code string
          console.log(xhr.getAllResponseHeaders); //Response headers
          console.log(xhr.response); //Response body
          result.innerHTML = xhr.response;
        }
      }
    };

POST request and set request headers

 //Create object
    const xhr = new XMLHttpRequest();
    //Initialize object
    xhr.open("POST", "http://127.0.0.1/server");
    //Set request header request header name, request header value
    //The request header can be customized, but the browser will report an error and needs to be set on the server side.
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //Send the request body content set here. The request body can be data in any format, provided that the server can process it.
    xhr.send("username=zhangya & amp;password=aaaaaa");
    //event binding
    xhr.onreadystatechange = function () {
      if (xhr. readyState === 4) {
        if (xhr.status >= 200 & amp; & amp; xhr.status <= 300) {
          result.innerHTML = xhr.response;
        }
      }
    };

When setting request headers, users can customize request headers, but custom request headers must be predefined on the server side, otherwise an error will be reported.

6. Solve the cache problem of IE browser

The IE browser caches the Ajax results. When the customer requests the same URL again, the data will be obtained from the local cache, and the latest data will not be obtained. For scenarios with strong timeliness, this will greatly affect the data. value. The following is sample code to solve this problem:

 //Create object
    const xhr = new XMLHttpRequest();
    //Initialize object
    xhr.open("POST", "http://127.0.0.1/server?t=" + Date.now());
    //Set request header request header name, request header value
    //The request header can be customized, but the browser will report an error and needs to be set on the server side.
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //Send the request body content set here. The request body can be data in any format, provided that the server can process it.
    xhr.send("username=zhangya & amp;password=aaaaaa");
    //event binding
    xhr.onreadystatechange = function () {
      if (xhr. readyState === 4) {
        if (xhr.status >= 200 & amp; & amp; xhr.status <= 300) {
          result.innerHTML = xhr.response;
        }
      }
    };

We only need to add a parameter that is different every time in the url. What is used here is to obtain the timestamp at that time. The timestamp at each time is different, and we do not need to manually change the parameter. In this way, the URL will be different every time, and there will be no caching.

7.Data conversion

What the server returns to us is generally a JSON string. Obtaining the data we want from the string will be more complicated. Of course, we can use the JSON.parse() method to manually convert the data into an object, or we can use the responseType of the instance object. Properties to automatically perform data processing, for example:

 const xhr = new XMLHttpRequest();
    //Automatically process data
    xhr.responseType = "json";

8. Solve request timeout and network problems

Look at the code first

xhr.open("GET", "http://127.0.0.1/time");
        // xhr.responseType = "json";
        xhr.setRequestHeader(
          "Content-Type",
          "application/x-www-form-urlencoded"
        );
        //Timeout setting 2s
        xhr.timeout = 2000;
        //timeout callback
        xhr.ontimeout = () => {
          alert("Request timeout, please try again later!");
        };
        //Network exception callback
        xhr.onerror = () => {
          alert("There seems to be a problem with your network!");
        };
        xhr.send("name=zhangsan & amp;age=18");
        xhr.onreadystatechange = () => {
          if (xhr. readyState === 4) {
            if (xhr.status >= 200 & amp; & amp; xhr.status < 300) {
              box.innerHTML = xhr.response;
            }
          }
        };

First we set a time of 2 seconds

xhr.timeout = 2000;

Then monitor this time

xhr.ontimeout = () => {
          alert("Request timeout, please try again later!");
        };

And set a timeout callback function for it. If the server does not respond to this request within this time, then this callback function will be triggered to give a prompt.

In addition, we set up an error callback function, which will also be triggered when an abnormality occurs in the network.

 xhr.onerror = () => {
          alert("There seems to be a problem with your network!");
        };

We can test by opening the developer tools and turning off the network

If you make a request after going offline, the corresponding alert will appear.

9. Handle the same request multiple times

If the user repeatedly makes the same request within a short period of time, before the server has time to respond, it will put a huge burden on the server. This is a very serious problem.

We can set an identification variable and then decide whether to initiate a request based on the value of the variable

 let xhr = null;
      //Indicate variables
      let isSending = false; //Whether the request is being sent
      btns[0].onclick = () => {
        //Determine whether the request is being sent. If yes, cancel the request.
        if (isSending) xhr.abort();
        xhr = new XMLHttpRequest();
        isSending = !isSending;
        xhr.open("GET", "http://127.0.0.1/time");
        xhr.send();
        xhr.onreadystatechange = () => {
          if (xhr. readyState === 4) {
            isSending = !isSending;
          }
        };

We set the initial value of isSending to false. At this time, the request is not sent. When sending the request, the value is inverted and it is not true. When the request is sent, the value is judged. If it is true, the abort method is called to cancel the request.

if (isSending) xhr.abort();

When the request is completed, the value is inverted to false. This way it won’t affect the next request.

10.The common form and general form of Ajax in Jquery

general form

$.get('http:127.0.0.1/server',{username:'zhangsan','age':18},(data)=>{
        console.log(data)
})

common form

$.ajax({
    url:'http://127.0.0.1/server',
    data:{username:'zhangsan','age':18},
    type:'GET',
    dataType;'json', //Response result processing
    success:(data)=>{
        console.log(data)
    },
    timeout:2000, //timeout time
    error:()=>{
        console.log('An error occurred!') //Error callback
    },
    headers: //Set request headers
})

11 Solving cross-domain issues

I believe this problem is a headache that troubles many people. Here we use CORS to solve this problem, that is, setting the response header on the server side to allow access to those requests that carry the response header we set to allow access.

Access-Control-Allow-Origin: http://example.com

Of course, we can also use a proxy on the server side to solve this problem.

Another way to solve this problem is JSONP. Many tags in the HTML markup language contain cross-domain features. For example, when we use script tags to reference external js, we need to import it from certain URLs, and our own files follow is the file protocol, and the imported files follow the http protocol. Cross-domain occurs here, but we do not report cross-domain errors when using these imported files. JSOP uses this principle to solve cross-domain problems. Here I won’t go into further details.

There are many other things that can perform server requests, such as axios, fetch, etc. If you are interested, you can find relevant information.