Async javascript and XML Asynchronous JS and XML
Ajax native JS operations
// Create an Ajax instance
let xhr = new XMLHttpRequest();// ActiveObject in IE
// Open request: some configuration items before sending a request
//1.HTTP METHOD:GET/POST/PUT/DELETE/HEAD/OPTIONS/TRACE/CONNECT/
//2. Url: interface address
//3. Async: Sets Ajax asynchrony. Default is asynchrony
//4. User-name /user-pass Indicates the user name and password
xhr.open(method, url, async, [user-name], [user-pass])
// Event listener: Generally listen for the readyStatechange event (Ajax statechange event), based on this event can get the response header response body returned by the server
xhr.onreadystatechange = (a)= > {
if(xhr.readyState === 4 && xhr.status === 200) {console.log(xhr.responseText); }};From this step, the current Ajax task starts. If Ajax is synchronous, subsequent code will not be executed until the Ajax state is successfulXhr.send ([request body content])Copy the code
Two, about HTTP request mode:
GET: Obtains data from the server
POST: pushes data to the server
DELETE: deletes some content on the server
PUT: Stores some content to the server
HEAD: Only the response header returned by the server, not the body’s content
OPTIONS: This is used to send a probe request to the server. If a message is returned, it indicates that the current client has established a connection with the server and can continue to execute other requests
TRACE: Axios: This Ajax library sends OPTIONS first when making cross-domain requests. If the server can be connected, further requests are sent.
GET and POST:
[Different ways of passing information to the server]
GET is passed through the URL string, and POST is passed through the request body
[GET]
xhr.open('GET'.'/tmp/list? xxx=xxx&xxx=xxx')
[POST]
xhr.send('xxx=xxx') (generally urL-encode format)Copy the code
GET is not safe. POST is relatively safe.
Because GET is based on “question mark passing parameter” to pass information to the server, easy to hack url hijacking, post is based on the request body.
GET creates an uncontrollable cache, POST does not.
Uncontrolled: is the browser’s independent memory, cannot be controlled by JS. The solution
xhr.open('GET'.`/temp/list? lx=1000&_=The ${Math.random()}`);
Copy the code
Other differences:
- GET is harmless when the browser falls back, while POST resubmits the request
- GET requests are actively cached by browsers, whereas POST is not, unless set manually
- GET request parameters remain intact in browser history, while POST does not
- GET requests can only be url encoded, while POST supports multiple encoding methods
Ajax state ready–state
0 => UNSENT The XHR is created and has not been sent
1 => OPENED has been OPENED
2 => HEADERS_RESERVED Ajax has been sent and the response header has been accepted by the client
3 => LOADING The response body is returning
4 => DONE The response body is received by the client
4. HTTP network status code status
The status code clearly reflects the result and cause of the current interaction
1XX: Indicating message – Indicates that the request has been accepted and processing continues
2XX: succeeded – Indicates that the request is successfully received
3XX: Succeeded but has been redirected
4XX: Client error
5XX: Server error
Specific examples:
200 OK: The client request is successful
206 Partial Content: The client sends a GET request with a Range header, and the server completes it
301 Moved Permamently: you have been permanently transferred to a new URL
302 Found: Temporary transfer to a new URL. When a server reaches the maximum number of concurrent requests, the server will transfer processing
304 Not Modified: The server tells the client that the original cache can continue to be used, such as CSS/JS/HTML/IMG,Ctrl+F5 304 cache invalid
400 Bad Request: The client has a syntax error that the server cannot understand
401 Unauthorized: The request is not authorized
403 Forbidden: Access to the requested page is Forbidden
404 Not Found: The requested resource does Not exist
413 Request Entity Too Large The content resource interacting with the server exceeds the maximum size
500 Interval Server Error Indicates a Server Error. The original cache is still available
503 Service Unavailable
XHR attributes and methods
Xhr. response Indicates the response body
Xhr.responsetext The contents of the response are strings (JSON or XML documents)
The content of the xhr.responsexml response is XML
Xhr. status HTTP status code returned
Xhr. statusText Description of the status code
Xhr. timeout Sets the timeout period of the request
xhr.timeout = 1000
xhr.ontimeout = (a)= > {
console.log(' Request timed out ')}Copy the code
Whether xhr.withCredentials are allowed across domains (false)
Xhr.abort () forces the interruption of an Ajax request
xhr.abort();
xhr.onabort = (a)= > {}
Copy the code
XHR. GetAllResponseHeaders () get all the response headers
Xhr.getresponseheader ([key]) for example, xhr.getresponseheader (‘date’) gets the server time in the response header
Xhr.open () opens the URL request
Xhr.overridemimetype () overrides the MIME type
Xhr.send () sends an Ajax request as a request body object
Xhr.setrequestheader () sets the custom request header, which must be set after open
/ / small example
xhr.onreadystatechange = (a)= > {
if(!/^(2|3)\d{2}$/.test(xhr.status))return;// Verify that the server has returned the content
if(xhr.readyState === 2) {let time = xhr.getResponseHeader('date');
}
if(xhr.readyState === 4 && xhr.status === 200) {JSON.parse(xhr.responseText); }}Copy the code
The difference between asynchronous and synchronous
Asynchronous:
let xhr = new XMLHttpRequest();
xhr.open('GET'.'xxx'.true);
xhr.onreadystatechange = (a)= > {
if(xhr.readyState === 2) {
console.log(1);
}
if(xhr.readyState === 4) {
console.log(2)
}
}
xhr.send();
console.log(3)
/ / 1 2 3
Copy the code
Synchronous:
let xhr = new XMLHttpRequest();
xhr.open('GET'.'xxx'.false);
xhr.onreadystatechange = (a)= > {
if(xhr.readyState === 2) {
console.log(1);
}
if(xhr.readyState === 4) {
console.log(2)
}
}
xhr.send(); // The task starts and nothing can be done until the current Ajax request is completed (readyState is not 4)
console.log(3)
//2 3 why?
// Due to synchronous programming, the main task queue is occupied by Ajax requests until the state becomes 4, and other events cannot be done.
// Therefore, the method can only be executed if readyState becomes 4.
let xhr = new XMLHttpRequest();
xhr.open('GET'.'xxx'.false);
xhr.send(); // The task starts and nothing can be done until the current Ajax request is completed (readyState is not 4)
// The current state is 4
xhr.onreadystatechange = (a)= > {
if(xhr.readyState === 2) {
console.log(1);
}
if(xhr.readyState === 4) {
console.log(2)}}console.log(3)
/ / 3
// Hence asynchronous Ajax
Copy the code
Ajax in jQuery
/** * DATA: * If a GET request is passed based on a question mark * if a POST request is passed based on a request body * DATA can be an object or a string: * If it is an object, Jq will convert objects to XXX = XXX mode (X-www-form-urlencoded) * data-type: pre-format the DATA to fetch the results TEXT/JSON/JSON/HTML/XML/SCRIPT (returned from the server to the client's response in the body of the content is generally string, * and set the DATA - TYPE = 'JSON', Jq internally converts the retrieved string to a JSON format object => It does not affect the result returned by the server, only secondary processing results) * ASYNC: set asynchronous * CACHE: set CACHE, when set to FALSE, and get request, JQ adds a random number to the end of the request URL * SUCCESS: callback function. When the Ajax request executes successfully, JQ executes the callback function with the result obtained in the response body (secondary processing) as an argument * ERROR: callback function executed after the request fails */
$.ajax({
url: 'xxx'.method: 'GET'.data: null.dataType: 'json'.async: true.cache: true.success: (result, textStatus, xhr) = > {},
error: (a)= >{}})Copy the code
Eight, invincible handwriting
Native JS encapsulates Ajax (jQ version)
~ function (window) {
function AJAX(options) {
return new AJAX.prototype.init(options);
}
function init(options = {}){
let {
url,
method = 'GET',
data = null,
dataType = 'JSON'.async = true,
cache = true,
success,
error
} = options;
//=>MOUNT MOUNT configuration items to the instance
['url'.'method'.'data'.'dataType'.'async'.'cache'.'success'.'error'].forEach(item= > {
this[item] = eval(item);
});
}
AJAX.prototype = {
constructor: AJAX,
init,
sendAjax(){
this.handleCache();
this.handleData();
//send
let {method, url, async, error, success} = this;
//SEND Sends a request
let xhr = new XMLHttpRequest();
xhr.open(method, url, async);
xhr.onreadystatechange = (a)= > {
if(xhr.readyState === 4) {if(!/^(2|3)\d{2}$/.test(xhr.status)){
error && error(xhr.statusText, xhr)
}
/ / processing DATA - TYPE
let result = this.handleDataType(xhr); success && success(result, xhr); }}; xhr.send(); }, handleDataType(xhr) {let dataType = this.dataType.toUpperCase(),
result = xhr.responseText;
switch (dataType) {
case 'TEXT':
break;
case 'JSON':
result = JSON.parse(result);
break;
case 'XML':
result = xhr.responseXML;
break;
}
return result;
},
handleCache() {
let {url, method, cache} = this;
if(/^GET$/i.test(method) && cache==false){
url += `The ${this.check()}=The ${+ (new Date()}`;
}
},
handleData() {
let {data, method} = this;
if(! data)return;
if(typeof data === 'object') {// if this is an object, we will set it to x-www-form-urlencoeded mode
for(let key in data){
if(data.hasOwnProperty(key)){
str += `${key}=${data[key]}`;
}
}
data=str.substring(0,str.length);
}
if(/^(GET|DELETE|HEAD|TRACE|OPTIONS)$/i.test(method)){
this.url += `The ${this.check()}${data}`;
this.data = null;
return;
}
this.data = data; //POST processing mode
},
check() {
return this.url.indexOf('? ') >- 1?'&':'? ';
}
}
init.prototype = AJAX.prototype;
window.ajax = AJAX; } (window)
Copy the code
Ajax with Native JS based on Promise (AxiOS version)
~ function (window) {
// Set the default configuration items
let _default = {
method: 'GET'.url: ' '.baseURL: ' '.headers: {},
dataType: 'JSON'.data: null./ / POST series
params: null./ / GET series
cache: true
};
// Manage Ajax based on the Promise design pattern
let ajaxPromise = function axios() {
let {
url,
baseURL,
data,
dataType,
headers,
cache,
params
} = options;
//=> Further process the passed parameters
if(/^(GET|DELETE|HEAD|OPTIONS)$/.test(method)){
/ / GET parameters
if(params) {
url += `${ajaxPromise.check(url)}${ajaxPromise.formatData(params)}`
}
if(cache === false){
url += `${ajaxPromise.check(url)}_ =The ${+ (new Date()}`
}
data= null;//GET series request body is empty
}else{
/ / POST series
if(data){ data = ajaxPromise.formatData(data); }}//=> Send Ajax based on Promise
return new Promise((resolve, reject) = > {
let xhr = new XMLHttpRequest();
xhr.open(method, `${baseURL}${url}`);
if(headers ! =null && typeof headers === 'object') {for(let attr in headers){
if(headers.hasOwnProperty(attr)){
let val = headers[attr];
if(/[\u4e00-\u9fa5]/.test(val)){
val = encodeURIComponent(val); } xhr.setRequestHeader(attr, headers[attr]); }}}//=> If headers exists, we need to set the request header
xhr.onreadystatechange = (a)= > {
if (xhr.readyState === 4) {if(/^(2|3)\d{2}$/.test(xhr.status)){
let result = xhr.responseText;
dataType = dataType.toUpperCase();
dataType === 'JSON'? result =JSON.parse(result):(dataType === 'XML'? result = xhr.responseXML :null);
resolve(result, xhr);
return;
}
reject(xhr.statusText, xhr);
}
}
xhr.send(data);
})
}
ajaxPromise.defaults = _default;
ajaxPromise.formatData = function formatData(){
let str = ` `;
for(let attr in obj) {
if(obj.hasOwnProperty(attr)){
str += `${attr}=${obj[attr]}& `;
}
return str.substring(0, str.length- 1)
}
}
ajaxPromise.check = function check(url){
return url.indexOf('? ') >- 1?'&':'? ';
}
/ / GET series
['get'.'delete'.'head'.'options'].forEach(item= > {
ajaxPromise[item] = (url, options = {}) = >{ options = { ... _default, ... options, url,method: item.toUpperCase()
};
returnajaxPromise(options); }})/ / POST series
['post'.'put'.'patch'].forEach(item= > {
ajaxPromise[item] = (url, data = {}, options = {}) = >{ options = { ... _default, ... options, url,method: item.toUpperCase(),
data
};
returnajaxPromise(options); }})window.ajaxPromise = ajaxPromise; } (window)
Copy the code
A little summary of Ajax, I hope to help you!