Five steps to using Ajax:

  1. Create an asynchronous object
  2. Set the request mode and address
  3. Send the request
  4. Listen for state changes
  5. Process the returned results

1. Create an asynchronous object XMLHttpRequest

Create Internet Explorer 5 and Internet Explorer 6 using the following methods:

var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
Copy the code

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) are created using:

var xmlhttp = new XMLHttpRequest;
Copy the code

So what do we do about browser compatibility? We can do this:

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
Copy the code

2. Set the request mode and address

To send requests to the server, we use the open() method of the XMLHttpRequest object.

xmlhttp.open("GET","test1.txt",true);
Copy the code
Method: Request type. GET or POST URL: location of file on server async: true or falseCopy the code

3. Send the request

     xmlhttp.send();
Copy the code

4. Listen for status changes

XMLHTTP. Onreadystatechange = function (ev2) {/ * 0: request uninitialized 1: the server connection has been established. 2: the request has been received 3:4: in the request processing Request completed, ReadyState === 4){// Check whether the request is successful. // The request is successful only when the status code is greater than 200, less than 300 or equal to 304 xmlhttp.status < 300 ||xmlhttp.status === 304){ 5. Process returned results // console.log(" received data returned by server "); success(xmlhttp); // Sucess is the parameter that encapsulates the Ajax function, as is error. }else{// console.log(" no data received from server "); error(xmlhttp); }}}Copy the code

5. Process the returned results

The processing was already done in the previous step to call the first function if data is received, and the second function otherwise.

6. Browser compatibility problems

6.1 Ajax Caching Mechanism

This problem occurs in Internet Explorer, where if a GET request is sent via Ajax, Internet Explorer assumes that there is only one result from the same URL.

Solution: Give the URL a different value every time it is requested. In this case, we can think of using the new Date().getTime() method to get a value to add to the URL.

Change the url here: “text1.txt? t=”+(new Date().getTime());

6.2 Differences in Creating Asynchronous Objects

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
Copy the code

7. Encapsulation Ajax

There are five steps each time you write Ajax, so the code is the same, and we can wrap it up in a function:

function obj2str(obj) { obj = obj || {}; Obj.t = new Date().getTime(); obj.t = new Date(). var res = []; For (var key in obj){// If Chinese characters need transcoding // you can call encodeURIComponent method // only letters/digits/underscores /ASCII codes can appear in URL res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key])); // [userName=lnj, userPwd=123456]; } return res.join("&"); // userName=lnj&userPwd=123456 } function ajax(url, obj, timeout, success, error) { // 0. Var STR = obj2str(obj); // key=value&key=value; // create an asynchronous object var XMLHTTP, timer; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // 2. Set request mode and request address /* method: request type; GET or POST URL: file location on server async: true (asynchronous) or false (synchronous) */ xmlhttp.open("GET", url+"?" +str, true); // 3. Send the request xmlhttp.send(); / / 4. Changes in the listening state XMLHTTP. Onreadystatechange = function (ev2) {/ * 0: request uninitialized 1: the server connection has been established. 2: the request has been received 3:4: in the request processing Request completed and response ready */ if(xmlhttp.readyState === 4){clearInterval(timer); / / determine if the request is successful the if (XMLHTTP status > = 200 && XMLHTTP. Status < 300 | | XMLHTTP. Status = = = 304) {/ / 5. Process returned results // console.log(" received data returned by server "); success(xmlhttp); }else{// console.log(" no data received from server "); error(xmlhttp); If (timeout){timer = setInterval(function () {console.log(" interrupt request "); xmlhttp.abort(); clearInterval(timer); }, timeout); }}Copy the code