preface
What I wrote earlier: the main knowledge point of this article is how to realize Ajax through native JavaScript. First, you need to have a little understanding of Json, HTTP network transmission protocol, network request mode, asynchronous programming, etc;
1. Implementation steps
- Create XMLHttpRequest object;
- Judge whether the request is successful through the onreadystatechange event;
- Request configuration (open)
- Send request (send)
1.1 create XMLHttpRequest object
XMLHttpRequest is a constructor that can be used to create instantiation of the object:
let xhr; xhr = new XMLHttpRequest();
Many browsers now have built-in XMLHttpRequest objects, but in order to be compatible with older browsers, the following method is used:
let xhr; new ActiveXObject("Microsoft.XMLHTTP");
1.2 judge whether the request is successful through the onreadystatechange event
In Ajax asynchronous communication, the client needs to send a request to the back end. In this process, it will involve the rule of three handshakes and four waves in TCP protocol;
The onreadystatechange event of XMLHttpRequest can be used to judge the request progress and request status of the current transaction
xhr.onreadystatechange = function(){ if(xhr.readyState != 4){ // When the readyState value is equal to 4, the request is completed return } if(xhr.status == 200){ // When the value of status equals 200, the request succeeds console.log(xhr.resposeText); // Data returned from the backend is received } else { console.log("request was aborted", xhr); } }
2.3 request configuration (open)
When the front end sends a request to the back end, it needs to use the open() method in the XMLHttpRequest object to configure the request:
xhr.open(method, url, async);
Parameter interpretation:
- Method: request method ("POST", "GET", "HEAD", "PUT", "DELETE");
- url: request address (determined by the interface document after communication with the back-end developer);
- async: Boolean value (asynchronous request or not, true means asynchronous request, false means asynchronous request is not used, generally asynchronous is used);
2.4 send request ()
When the front end sends a request to the back end, it needs to use the send() method in the XMLHttpRequest object to send it:
xhr.send(String);
Parameter interpretation:
- String: the data information carried when sending a request;
be careful:
- When the request type is "POST", this parameter is the data information carried by the "POST" request (if there is no data information, you can also fill in "null");
- When the request type is "GET", this parameter is filled in as "null", because the data information of "GET" request type must be written in the url request address, starting with "?" and connected with "&", such as:? key=value&key=value
2. Comprehensive demonstration
Handle Ajax asynchronous operations through Promise objects
function myAjax({ method = "GET", // The request method setting defaults to GET request url = null, // The request path defaults to null data = null, // The carried data is null by default async = true, // The default is asynchronous request timeout = 3000 // Request time }) { return new Promise((resolve, reject) => { // ajax implementation steps let xhr; // Compatibility judgment if (window.XMLHttpRequest) { xhr = new XMLHttpRequest() } else if (window.ActiveXObject) { // Low version IE processing xhr = new ActiveXObject("Microsoft.XMLHTTP") } // Event handling: judge whether the request is successful or not by reviewing the event onreadystatechange /* * readyState Value: * 0: Uninitialized, i.e. no call to open(); * 1: After startup, open() has been called, but send() has not been called; * 2: Send, call send(), but no response is received; * 3: Receiving, the response body has not been received; * 4: Complete and receive all response data. * * status Value: * xmlHttpRequest The status of the object represents the status of the current http request and is a long integer data * */ xhr.onreadystatechange = function () { if (xhr.readyState != 4) { return } if (xhr.status == 200) { console.log(JSON.parse(xhr.responseText)) // Because string data is received by default, it is converted to an Object object resolve(JSON.parse(xhr.responseText)) } else { // console.log("request failed", xhr) reject(xhr) } } // Set request timeout xhr.timeout = timeout; // Distinguish GET requests from POST requests if (method === "GET") { // Request configuration // The Get request parameter must be placed on the url in order to? At the beginning? key=value&key=value xhr.open(method, url + "?" + formatData(data), async) // Send request xhr.send(null) } else if (method === "POST") { // Request configuration // POST requests can be made without writing url parameters xhr.open(method, async) // The POST request needs to set the request header after open and before send xhr.setRequestHeader("Content-type", "application/x-www-form-urlencodeed") //Send request //POST submits data here xhr.send(formatData(data)) } }) } // Processing data for get requests // Process the data and format it into the data we want: key = root & value = root function formatData(data) { if (data instanceof Object) { let arr = [] for (let key in data) { arr.push(key + "=" + data[key]) } return arr.join("&") } return data }
Related articles
- NodeJs - module
......