preface

XMLHttpRequest is a browser interface that allows Javascript to communicate with HTTP(S).

Originally, Microsoft introduced this interface in Internet Explorer 5. It was so useful that other browsers copied it and ajax operations were born.

There are two versions of this interface. Let’s look at the two versions: the old version and the new version

An older version of the XMLHttpRequest object

The older version is used as follows:

  1. First, create a new instance of XMLHttpRequest
var xhr
= new XMLHttpRequest();
Copy the code
  1. Then, an HTTP request is made to the remote host :(first opened then sent)
xhr.open('GET'.'example.php'); // xhr.open(request, request URL (GET))
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded'); // Customize the header field
xhr.send(); // Initiate a request and send parameters (POST mode)
Copy the code
  1. It then waits for the remote host to respond. At this time needmonitoringThe XMLHttpRequest objectChange of state, specifying the callback function
xhr.onreadystatechange = function(){
    if ( xhr.readyState == 4 && xhr.status == 200 ) {
        alert( xhr.responseText );
    } else{ alert( xhr.statusText ); }};Copy the code

The code above contains the main attributes of the older version of the XMLHttpRequest object:

  • Xhr. readyState: of the XMLHttpRequest objectstateIs equal to4Indicates that the data has beenAfter receiving.
  • Xhr. status: returned by the serverStatus code, equal to 200 means everything is normal.
  • Xhr. responseText: returned by the serverThe text data
  • Xhr. responseXML: returned by the serverXML formatThe data of
  • Xhr. statusText: returned by the serverState the text.

Disadvantages of the older version

Older versions of the XMLHttpRequest object have several disadvantages:

  • Only text data can be transmitted, not read or uploadedBinary file
  • When transmitting and receiving data,No progress information, can only indicate whether completed
  • Affected by the “same origin policy”, only toThe same domain nameRequest data from the server

Features of the new version

The new version of the XMLHttpRequest object addresses the shortcomings of the previous version with significant improvements:

  1. Can be set for HTTP requestsTime limit
  2. You can use FormData object managementThe formdata
  3. You can uploadfile
  4. Can get data transmissionThe progress ofinformation
  5. Can request data under different domain names (Cross-domain request)
  6. You can get the server sidebinaryThe data.

1. HTTP request duration

Sometimes ajax operations are time-consuming and take an unpredictable amount of time. If the connection speed is slow, users may have to wait a long time.

The new version of the XMLHttpRequest object adds the timeout attribute, which allows you to set the time limit for HTTP requests

xhr.timeout = 3000;
Copy the code

The above statement sets the maximum wait time to 3000 milliseconds. After this time limit, HTTP requests are automatically stopped. Accompanying this is the onTimeout event, which specifies the callback function

xhr.ontimeout = function(event){
    alert('Request timed out! ');
}
Copy the code

2. The FormData object

Ajax operations are often used to pass form data. To facilitate form processing, HTML5 has added a FormData object that simulates forms

  1. First, create a new FormData object:
var formData = new FormData();
Copy the code
  1. Then, add form items to it
formData.append('username'.'Joe');
formData.append('id'.123456);
Copy the code
  1. Finally, pass the FormData object directly. This has to do withSubmit web formExactly the same effect
xhr.send(formData);
Copy the code

The FormData object can also be used to get the value of a web form

var form = document.getElementById('myform');
var formData = new FormData(form);
formData.append('secret'.'123456'); // Add a form item
xhr.open('POST', form.action);
xhr.send(formData); // Send the form
Copy the code

3. Upload files

The new XMLHttpRequest object can not only send text messages, but also upload files.

Suppose files is a “select file” form element (input[type=”file”]), we load it into a FormData object, and then send the FormData object

var formData = new FormData();
for (var i = 0; i < files.length; i++) { formData.append('files[]', files[i]);
}
xhr.send(formData);
Copy the code

4. Obtain progress information

The new version of the XMLHttpRequest object has a progress event that returns progress information when transmitting data.

It is divided into upload and download cases:

  • downloadThe Progress event belongs toXMLHttpRequestobject
  • uploadThe Progress event belongs toXMLHttpRequest.uploadobject
  1. Start by defining the callback function for the Progress event
xhr.onprogress = updateProgress;
xhr.upload.onprogress = updateProgress;
Copy the code
  1. Then, inside the callback function, use some properties of the event
function updateProgress(event) {
    if (event.lengthComputable) {
        varpercentComplete = event.loaded / event.total; }}Copy the code

In the code above:

  • Event. total is the total number of bytes that need to be transmitted
  • Event.loaded is the bytes that have been transferred
  • If event.lengthComputable is not true, event.total equals 0

Related to the Progress event, there are five other events that can specify callback functions:

  • Load event: The transfer completes successfully
  • Abort event: The transfer is canceled by the user
  • Error Event: An error occurred during transmission
  • Loadstart event: Transfer starts
  • LoadEnd event: Transfer ends without knowing whether it succeeded or failed

5. Cross-domain Resource Sharing (CORS)

A new version of the XMLHttpRequest object that makes HTTP requests to servers with different domain names. This is called Cross-origin Resource Sharing (CORS).

Prerequisites to use “cross-domain resource sharing” : 1. The browser must support this feature, and 2. The server side must agree to this “cross-domain”. If the above conditions are met, the code is written exactly as if it were a non-cross-domain request

xhr.open('GET'.'http://other.server/and/path/to/script');
Copy the code

Read more about CORS in the Browser series – Cross Domain

Refer to the article

  • XMLHttpRequest object – W3school
  • XMLHttpRequest Level 2 User Guide – Ruan Yifeng’s network logs