The problem: Too much code to send an Ajax request once, and redundant and repetitive code to send multiple requests

Solution: Encapsulate the request code in a function that is called when the request is sent

1. Simplified version

Function ajax (mether, url, callback, data, flag) {/ / is asynchronous, the asynchronous flag = flag | | true; let xhr; // The request method is converted toUpperCase mether = mether.toUpPerCase (); If (window.XmlHttpRequest) {XHR = new XmlHttpRequest ()} else if (window.ActiveXObject) {XHR = new Xhr.onreadystatechange = function() {if (xhr.readyState === 4 &&xhr.status === 200) { Callback (xhr.responseText)}} ' '; if (mether === 'get ') {let date = new date (); let timer = date.getTime();"GET", url + '? ' + data + '&timer' + timer, flag); } else if (mether === 'post ') {' post ', url, flag); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.send(data) } }

Note: The time parameter is added to the GET request to solve the caching problem

In lower versions of Internet Explorer, Ajax has serious caching issues. With the address of the request unchanged, only the first request is actually sent to the server, and subsequent requests are retrieved from the browser’s cache. As a result, even if the server’s data is updated, the client will still get the old data in the cache

The solution is to request parameters at the end of the request address, ensuring that the value of the request parameter is different in each request

So add a real-time time to each send so that the request parameters are different each time

2. Detailed version

The above simplified version of the default is to handle the data, that is, in the incoming to handle the data

This method adds methods for successful and unsuccessful requests

Function Ajax(options) {// let defaults = {method: 'GET', url: '', data: {}, header: {' content-type ': 'application/x-www-form-urlencoded' }, success: function() {}, error: Function () {}} // options replace the same Object. Assign (defaults, Options) / / request means capital defaults. The method = defaults. Method. The toUpperCase () let XHR. If (window.XMLHttpRequest) {XHR = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject(); } // ListeningonReadyStateChange = function() {if (xhr.readyState === 4) {// Get the response header let contentType = xhr.getResponseHeader('Content-Type'); // Let ContentText = xhr.responseText; If (contentType === 'application/ JSON ') {contentText = JSON.parse(contentText)} // If (contentType === 'application/ JSON ') {contentText = JSON.parse(contentText)} // When the HTTP status code is 200, If (xhr.status === 200) {default.success (contentText, contentText) {default.success (contentText, contentText); XHR) // otherwise call error function} else {defaults.error(contentText, contentText) XHR)}}} let params = "for (let key in {params += key + '=' + [key] + '&'} // delete last character & params = params.substr(0, params.length - 1); // if (defaults.method === 'GET') {// Need to concatenate the request address defaults.url = defaults.url + '? ' + params; } // Configure request mode and path, default) If (defaults.method === 'POST') {let contentType = defaults.header[' content-type ']; // Set the header xhr.setRequestHeader('Content-Type', ContentType); // If you want to send a JSON object, If (contentType == 'application/ JSON ') {XHR. Send (json.stringify ( // } else {xhr.send(params)} else {xhr.send();} else {xhr.send(); }};

One of the biggest differences between GET and POST requests is the way the data is sent

  • GETA request is the concatenation of data with the request address
  • POSTThe request is to pass the datasend()Sending to the server

What they all have in common is that the data needs to be concatenated into namer=xxx&age= XXX

However, the POST request needs to set the header:

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

To send data as a JSON string, you need to first convert the JSON object to a JSON string. And you need to use a POST request

JSON. Stringify (JSON object)

Call the wrapped Ajax function:

Prerequisite: The function needs to be preceded

Ajax ({/ way/request method: "post", / / request address url: 'http://localhost:3000/cache', / / to use JSON object to send data in the form of header: {' the content-type: 'application/json'}, data: {namer: 'XHR ', song:' just right '}, success: function(data, XHR) {console.log(' request successful '); console.log(data); console.log(xhr); }, error: function(data, XHR) {console.log(' Request failed '); console.log(xhr); console.log(xhr.getResponseHeader); }});