Coding With Fun
Home Docker Django Node.js Articles FAQ

Basic use of AJAX


May 30, 2021 Article blog


Table of contents


I. What is ajax?

  • ajax is a technique that updates parts of an entire page without having to reload it.
  • AJAX - Asynchronous JavaScript and XML (asynchronous JavaScript and XML).
  • Traditional web pages (without AJAX) must overload the entire page if they need to be updated. a jax uses a small amount of data exchange with the server in the background, which means that parts of the page can be updated without reloading the entire page.  Basic use of AJAX1

Basic use

function loadData() {
   let xhr;
   if (window.XMLHttpRequest) {
     xhr = new XMLHttpRequest();
  } else {
     xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }

   xhr.onreadystatechange = function () {
     if (xhr.readyState === 4 && xhr.status === 200) {
       console.log(xhr.responseText);
    }
  }

   xhr.open("GET","http://127.0.0.1:3001/users",true);
   xhr.send();
}

3. Explain the code above

3.1 Create an XML HttpRequest object

All modern browsers (IE7 plus, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects. The syntax for creating XMLHttpRequest objects: let xhr s new XMLHttpRequest();

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects: let xhr s newXObject ("Microsoft.XMLHTTP");

So to deal with all modern browsers, including IE5 and IE6, you should check that the browser supports XMLHttpRequest objects. I f so, create an XMLHttpRequest object. If not, create ActiveXObject:

let xhr;
if (window.XMLHttpRequest) {
 xhr = new XMLHttpRequest();
} else {
 xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

3.2 Send a request to the server

xhr.open("GET","http://127.0.0.1:3001/users",true);
xhr.send();

(1) The open (method, url, async) method specifies the type of request, the URL, and whether the request is processed asynchronously.

  • method: The type of request; GET or POST
  • url: The location on the server to access
  • async:true (asynchronous) or false (sync)

(2) Send (string) sends the request to the server

  • Parameter string: Only for POST requests

3.3 Receive a response from the server

For a response from the server, use the responseText or responseXML properties of the XMLHttpRequest object.

  • ResponseText: Gets response data in the form of strings
  • Response XML: Get response data in XML form

3.4 Onreadystatechange event

When a request is sent to the server, we need to perform some response-based tasks. T he onreadystatechange event is triggered whenever readyState changes. The readyState property contains status information for XMLHttpRequest.

(1) onreadystatechange: This function is called whenever the readyState property changes.

(2) ReadyState: The status of XMLHttpRequest is present. Changes from 0 to 4.

  • 0: The request is not initialized
  • 1: The server connection has been established
  • 2: The request has been received
  • 3: The request is in process
  • 4: The request is complete and the response is ready

(3)status

  • 200: “OK”
  • 404: Page not found

(4) In the onreadystatechange event, we specify the tasks that the server performs when it is ready to be processed. When readyState is equal to 4 and has a status of 200, the response is ready.

Note: The onreadystatechange event is triggered 4 times (0 - 4) for each change in readyState: 0-1, 1-2, 2-3, 3-4.

xhr.onreadystatechange = function () {
 if (xhr.readyState === 4 && xhr.status === 200) {
   console.log(xhr.responseText);
}
}

4. Other ways

//第一个参数是请求路径,第二个参数是一个函数,当拿到数据后调用该函数
function get(url,callback) {
 let xhr = new XMLHttpRequest();
 //当请求加载成功之后要调用该函数
 xhr.onload = function() {
   callback(xhr.responseText);
}
 xhr.open('get',url)
 xhr.send();
}

get('http://localhost:3001/users',function (data) {
 console.log(data);
});

4.1 Extension

We can rewrite the code above to support Promise so that we can make chain calls

function get(url) {
 return new Promise(function (resolve, reject) {
   let xhr = new XMLHttpRequest();
   xhr.onload = function () {
     //使用JSON.parse()将拿到的数据转成JS对象
     resolve(JSON.parse(xhr.responseText));
  }
   xhr.open('get', url)
   xhr.send();
})
}

Chain calls:

let data = {};
get('http://localhost:3001/users')
.then(function (userData) {
  data.user = userData;
  return get('http://localhost:3001/jobs')
})
.then(function (jobsData) {
  data.jobs = jobsData;
  console.log(data);
})