First, native JS implementation AJAX
JS implementation AJAX is based primarily on browser-provided XMLHttpRequest (XHR) classes, all modern browsers (ie7+, Firefox, Chrome, Safari, and Opera) are built XMLHttpRequest objects.
1. Get the XMLHttpRequest Object
// get XMLHttpRequest Object var New XMLHttpRequest ();
2. Send an HTTP request
Next, we need to open a URL and then send the request. The XMLHttpRequest Open () method and the Send () method are used respectively.
Open () accepts three parameters: the type of request to be sent ("get", "post", etc.), the requested URL, and a Boolean value that indicates whether the request was sent asynchronously
Here is an example of calling this method.
Xhr.open ("get""url"false);
If the first parameter is GET, you can put the argument directly behind the URL
If the first parameter is POST, you need to write the parameter in the Send () method. The parameters of the Send () method can be any data that you want to send to the server. The data is sent to the server in the form of a string
Name=admint&password=root. Or you can pass data in JSON format:
// set Content-type to Application/jsonxhr.setrequestheader ('content-type' application/json'); // Pass the JSON string xhr.send (json.stringify ({username:'admin', Password:' root' });
If the request header is not set, native AJAX defaults to sending the data by using Content-type. Text/plain;charset=utf-8.
If you do not need to send data through the request principal, you must pass in NULL, because this parameter is required for some browsers. After calling send (), the request is dispatched to the server.
After the response is received, the data for the response is automatically populated with the properties of the XHR object.
ResponseText: The text to be returned as the response body.
Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the XML DOM document containing the response data.
Status: The HTTP status of the response.
Description of the Statustext:http status.
3. Handling the response of the server
When sending a request, we need to specify how to handle the server's response, and we need to use the onReadyStateChange property to detect the server's response status.
Xhr.onreadystatechange = function () { if4) { if - 304 ){????? alert (xhr.responsetext); Else { alert ("" + xhr.status); }};
Second, jQuery to achieve AJAX
There has been a lot of improvement in compatibility and ease of use, making AJAX calls very simple.
<script type= "Text/javascript" src= "./jquery-3.2.1.min.js" ></script>
//GET$.Get('/api', Function (res) {//Do something});//POSTvardata ={username:'Admin', Password:'Root'};$.post ('/api', data, function (res) {//Do something});
Third, Fetch API
While using JQuery can greatly simplify the use of XMLHttpRequest, XMLHttpRequest is inherently but not a well-designed API: + non-conforming separation of concerns (separation of concerns)
Principles + Configuration and invocation are very confusing + use event mechanism to track state changes + event-based asynchronous model no modern promise,generator/yield,async/await-friendly
The fetch API is designed to fix these flaws by providing the same JS syntax as the HTTP semantics, which, in short, introduces a practical way to fetch network resources.
The browser compatibility diagram for Fetch is as follows:
1. An example of using Fetch
First look at a simple Fetch API example?? :
Fetch ('/api', {method: ' Get '}). Then (function (response) { return Response.json ();}). Then (function (data) { console.log (data);}). Catch (function (Error) { console.log (', error);});
After using the ES6 arrow function:
Fetch ('/api'). Then (response = Response.json ()) = Console.log ( Data)) . Catch (Error = Console.log (", error))
AJAX XHR, JQuery, Fetch comparison