AJAX: Asynchronous JavaScript and XML
1. Create using XMLHttpRequest
function success(text) { console.log('Success:' + text); } function fail(code) { console.error('Error Code: ' + code); } // New XMLHttpRequest object var request = new XMLHttpRequest(); // When the state changes, the callback function is executed request.onreadystatechange = function() { // Determine whether the request has been completed if(request.readyState === 4) { // Judgment of response results if(request.status === 200) { // The request succeeds and the response data is returned return success(request.responseText); } else { // Failed request, return status code return fail(request.status) } } else { // The Http request is still in progress. } } // Send Http requests request.open('GET', '/api/test'); request.send(); alert('Request sent, please wait for response...')
Main points:
- It is often seen whether browsers support XMLHttpRequest: window. XMLHttpRequest.
- Create an XMLHttpRequest object: var request = new XMLHttpRequest();
-
Common attributes of the XMLHttpRequest object:
- onreadystatechange
- readyState (request status code, 4 indicates that the request has been completed)
- Status (response status code, 200 indicates correct response)
- responseText
-
Common methods for XMLHttpRequest objects:
-
open() (this method has three parameters)
- Parameter 1: Specify the request method (GET/POST/HEAD)
- Parametric 2: Specify the URL (Note: The URL is the relative path)
- Parametric 3: Specifies whether it is asynchronous (true / false), defaulting to true
-
send() (true send request, this method has one parameter)
- If you create a POST request, you need to pass the parameter body
- If you create a GET request, you can omit the parameter or pass null
-
2. Create with ActiveXObject
// Just change the XMLHTTPRequest() to ActiveXObject('Microsoft.XMLHTTP'). var request = new ActiveXObject('Microsoft.XMLHTTP');
Because the attributes and methods of the ActiveXObject object are the same as those of the XMLHTTPRequest object:
// Therefore, it is possible to integrate standard writing with low-level IE writing. var request; if(window.XMLHTTPRequest) { request = new XMLHTTPRequest(); } else { request = new ActiveXObject('Microsoft.XMLHTTP') }
3. Create with JQuery
var xhr= $.ajax('/api/test',{ dataType: 'json' }); // No open() send() is required, and the request is executed after creation. // The xhr object created by jQuery is similar to a Promise object xhr.done((data) => { console.log('Success: ' + JSON.stringify(data)); }).fail((xhr, status) => { console.error('Error: ' + xhr.status + ', Reason: ' + status); }).always(() => { console.log('Request completed: Called regardless of success or failure'); });
Main points:
-
The $. ajax() method contains two parameters
- Parametric 1: Request URL;
- Parametric 2: An optional setting object;
-
setting configuration
- async: is it an asynchronous request by default true?
- Method: http request method, default is'GET', can also be set to'POST','PUT';
- Headers: additional http request headers, which need to be object objects;
- Data: The data sent can be strings, arrays or objects.
- contentType: The format for sending POST requests, by default,'application/x-www-form-urlencoded', or'text/plain','application/json', etc.
- Data Type: The format of the data can be'html','json','text', etc. The default values are automatically determined according to contentType.
-
jQuery ajax grammatical sugar:
-
get(): Send a get request, the second parameter can be an object, and jq splices automatically into a string
$.get('api/test',{ name: 'huang xin', age: 18 }) // Equivalent to / API / test? Name = huang% Xin & age = 18
-
post(): Send a post request, and the second parameter is serialized by default application/x-www-form-urlencoded
$.post('api/test',{ name: 'huang xin', age: 18 }) // Send a post request with name = huang% Xin & age = 18 as body
- getJSON(): Send a get request and return a JSON object;
-
4. Create with promise
// ajax will return the promise object function ajax(method, url, data) { let request = new XMLHttpRequest(); return new Promise((resolve,reject) => { request.onreadystatechange = () => { if(request.readyState === 4) { if(request.status === 200) { resolve(request.responseText); } else { reject(request.status); } } } request.open(method,url); request.send(data); }); } var p = ajax('GET','/api/test'); p.then((text) => { // ajax succeeded in getting the response content; console.log('Success: ' + text); }).catch((code) => { // ajax fails and gets the status code. console.error('Error Code: ' + code); })