1. Create an XMLHttpRequest asynchronous object
var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
    if (xmlhttp.overrideMimeType) {
        xmlhttp.overrideMimeType("text/xml"); }}else if (window.ActiveXObject) {
    var xmlList = ["MSXML2.XMLHTTP"."Microsoft.XMLHTTP"];
    for (let i = 0; i < xmlList.length; i++) {
        try {
            xmlhttp = new ActiveXObject(xmlList[i]);
        } catch (e) {
            console.log("error"+ e); }}}if(! xmlhttp) {console.log("Failed to create xmlHttprequest object");
}
Copy the code
  1. Set the request mode and address
xmlhttp.open("GET"."? name=rel&class=1".true);
// Note that the following configuration is required for post requests:
xmlhttp.open("POST"."? name=rel&class=1".true);
xmlhttp.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
Copy the code
  1. Send a request
xmlhttp.send();
// If the request is post
xmlhttp.send("name=rel&class=1");
Copy the code
  1. Create a callback function that listens for state changes
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState === 4) {
        if (xmlhttp.status == 200) {
            console.log("Receive returned data" + xmlHttp.responseText);
        } else {
            console.log("No returned data received"); }}}// ReadyStates of Ajax
 //0 - (uninitialized) The send() method has not been called yet
 //1 - (load) The send() method has been called and the request is being sent
 //2 - (load completed) The send() method is complete and all responses have been received
 //3 - (interaction) Parsing the response content
 //4 - (done) The response content is parsed and can be invoked on the client
Copy the code

  1. Receive returned data
The HTTP status code of the response200: The response succeeded.301: Permanent redirect/permanent transfer302: Temporary redirect/temporary transfer304: Data is obtained from the cache400: Request parameters are incorrect401: No access permission404: The accessed resource does not existCopy the code