1. Introduce the Ajax

1.1 Asynchronous JavaScript and XML Ajax is a technique for updating parts of a web page without having to reload the entire page. It is a local refresh technique that dynamically creates a web page.

1.2 create Ajax

(function(global,factory){
// In node.js
    if(typeof module= = ='object'&&typeof module.exports==='object') {// Import modules
    const XMLHttpRequest=require('xmlhttprequest-ssl').XMLHttpRequest;
    factory(module.exports,XMLHttpRequest);
    }else{// Browser environment
    factory(global,XMLHttpRequest);
    }
})(typrof window! = ='undefined'?window:this.(global,XMLHttpRequest) = >{
    // Create an XMLHttpRequest object
    const xhr=new XMLHttpRequest();
    / / get request
    const get=(url,callback) = >{
    processRequest('get',url,null,callback);
    }
    / / post request
    const post=(url,data,callback) = >{
    processRequest('post',url,data,callback);
    }
    // Process the request
    const processRequest=(method,url,data,callback) = >{
    // Initialize the requestxhr.open(method,url); -8
    if(null! ==data) data=JSON.stringify(data);// Convert object data to a string
    // Set the request header
    xhr.setRequestHeader("Content-Type"."application/json; charset=utf-8");
    // Set the request header
    xhr.onerror=errorHandler;
    // A request was made
    xhr.send(data);
    // Accept data
    xhr.omload=() = >{
    if(xhr.status==200){
        callback({status:200.msg:"ok".daya:xhr.responseText})
        }esle{
        callback({status:xhr.status,msg:"Server request error", data: xhr.responsetext})}}// Handle the error request
    const errorHandler=() = >{
    console.log("Server request error....");
    }
    // Expose the interface
    global.$get=get;
    global.$post=post;
});    
    
Copy the code

Encapsulate an Ajax with Node.js

1.3 Advantages and disadvantages of Ajax

1.3.1 Advantages of Ajax

  1. Asynchronous interaction is realized and user experience is improved.
  2. Instead of reloading the entire page, only a small amount of data exchange with the server is required to update a portion of the page, thus reducing the bandwidth footprint.
  3. Ajax runs on the client side, taking over some of the work that the server would otherwise do, reducing the load on the server with multiple users.

1.3.2 Disadvantages of Ajax

  1. Security issues, heavy use of Ajax exposes the details of server interactions.
  2. Not easy to debug.
  3. Search engine support is weak.