Article Directory
I. INTRODUCTION
Ajax is a way to request additional data to the server without a page written in technology, it can bring a better user experience and change the past, "click and wait" mode of interaction can be achieved without refreshing the page loads.
[ Note ] In fact, ajax can be run in a non-server environment, but for some reason, ajax requested documents must be in a server environment, resulting in a server environment should ajax
1.1 advantages and disadvantages
advantage
- No refresh the page is loaded
- Improved user experience
- Improved page rendering speed
Shortcoming
- No forward and backward history
- Search engines can not retrieve the data js caused by the change, the destruction of SEO
1.2 XHR
The core of Ajax is the XMLHttpRequest object (referred XHR), XHR to send a request to the server and parsing server response provides a smooth interface (i.e. the connection to the front and rear ends, carrying data interaction). With more information can be obtained from the server asynchronously, meaning after the user clicks, you can not refresh the page can also obtain new data. In other words, you can use the XHR object to obtain new data, and then through the DOM to insert new data into the page.
1.2.1 Properties
-
the responseText : the text returned as the respective body
-
the responseXML : If the appropriate content type is "text / xml" or "application / xml", save this property will contain the details of the XML DOM document data
-
Status : the appropriate HTTP status
- 1 **: Request received, continuing process
100-- customers must continue to make requests
101-- client asks the server to convert the HTTP protocol version upon request - 2 **: operating successfully received, analyzed, accepted
200-- trading success
201-- prompted know the URL of the new file
202-- accept and process, but the process is not completed
203-- return uncertain or incomplete information
204-- requests received, but no information is returned
completed request 205-- server, the user agent must reset the current document has been visited
206-- server has completed GET request some users - 3 **: Complete this request must be processed further
resources 300-- request can be obtained in many
301-- deletion request data
302-- address found in other requested data
303-- advise clients to access the URL or other access methods
304- - the client has performed a gET, but the file does not change
the resource 305-- must be requested from the server specified address
codes 306-- previous version of HTTP used in the current version is no longer used
resources 307-- stated request delete temporary - 4 **: The request contains a syntax error or can not be completed
400-- Bad Request, such as syntax errors
401-- request authorization failed
402-- retains effective response ChargeTo head
403-- request does not allow
404-- not find a file, or query the URl
405-- request-Line method in the user defined field allowed
406-- Accept transmitted from the user according to drag, the requested resource is inaccessible
407-- 401 Similarly, the user must first be authorized on the proxy server
408-- no client completion request in a user-specified time hungry
409-- current resource status of the request can not be completed
no longer on the server resource and 410-- no further reference address
411-- Content-Length server rejected the user-defined attribute request
412 - one or more fields in the request header error current request
the resource request is greater than 413-- server allows
the resource server 414-- requested URL is longer than the length allowed
415-- requested resource does not support the requested item format
416-- range request includes a request header fields, not the current value in the indicated range request resources, the request If-Range request does not contain a header field
417-- Expect server does not meet the request header field specifies the expected value, if a proxy server may be a server can not satisfy the request - 5 **: server to perform a perfectly valid request failed
500-- generate an internal server error
function 501-- server does not support the requested
502-- server is temporarily unavailable, and sometimes in order to prevent system overload
503-- server overload or suspend service
504-- overload mark, use another gateway server in response to a user or service, a long wait time setting
505-- server does not support the request or reject branched HTTP version specified in the header
- 1 **: Request received, continuing process
-
statusText : Description HTTP status
-
the readyState : currently active phase request / response process
- 0: not initialized. open has not been called () method
- 1: Start (load). It has been called open () method, but not send call () method
- 2: Send (load completion). It has been called send () method, but has not yet received a response
- 3: receiving (interactive). A partial response has been received
- 4: Complete (complete). It has received all the response data, and is ready to use at the client
As long as the value of redayState property by a programmed value to another value, it triggers a readystatechange event. This event can be used to detect the value of readyState after each change of state. Usually, we only take care of readyState value of 4 stages, because this issue have been ready all the time.
1.2.2 Method
open()
- The type of requests: get or post
- GET is the most common type of request, it is most commonly used as a server query certain information. If necessary, you can query string parameters appended to the end of the URL in order to send information to the server
- POST POST request after the GET frequency generally should be saved for transmitting data to the server. post request should request the data submitted as a host, the GET request is not the case conventionally. POST request body may contain a lot of data, but the format is not limited.
- [Note] POST GET request resource consumption than more, from a performance point of view, in order to transmit the same data basis, the GET request speed can be up to twice the POST request.
- Request URL:
- Whether an asynchronous transmission request Boolean
var ajax = newXMLHttpRequest();
ajax.open("get","example.php",true);
For example, two lines of code is to initiate a GET request for example.php, call the open () method does not actually send the request. But only a start request for delivery.
[Note] can only be used to send requests for the same URL ports and protocols to the same domain. If the requested page URL and start some differences will lead to a security error.
send ()
to send a particular request, the following must be such as call send () method
var ajax = newXMLHttpRequest();
ajax.open("get","example.php",true);
ajax.send(null);
Here send () method takes one parameter, i.e. the data to be sent in the body of the request, if the request does not need to send data over the body, it must pass null, since this parameter for some browsers is required. After calling send () method, the request is dispatched to the server.
the setRequestHeader ()
This method may be provided a custom request header information, this method takes two parameters: the name and value of the header field of the header field. To successfully send a request header information, and the call must send after calling open () method () method before calling setRequestHeader () method
- Json format data transmission
xhr.setRequestHeader ( "Content-type", "application / json; charset = utf-8"); - Form data
xhr.setRequestHeader ( "Content-type", "application / x-www-form-urlencoded; charset = utf-8"); - Sending plain text (not specified Content-type, this is the default)
xhr.setRequestHeader ( "the Content-type", "text / Plain; charset = UTF-. 8"); - Html text transmission
xhr.setRequestHeader ( "Content-type", "text / html; charset = utf-8"); - With or without encoding a
@ character encoding without writing xhr.setRequestHeader ( "Content-type", "application / json"); - Value is not case sensitive (but try lowercase)
xhr.setRequestHeader ( "the Content-type", "the Application / the JSON; charset = UTF-. 8");
Second, the package
2.1 ajaxGet
function ajaxGet(url,data){
data = data || {};
var str = '';
for(var i in data){
str = str + i + "=" + data[i] + "&";
}
var d = new Date();
url = url + "?" + str + "__qft="+d.getTime();
var p = new Promise(function(success,error){
var ajax = new XMLHttpRequest();
ajax.open("get",url,true);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
success(ajax.responseText);
}else if(ajax.readyState == 4 && ajax.status != 200){
error(ajax.status);
}
}
ajax.send();
})
return p;
}
2.2 ajax post
function ajaxPost(url,data){
data = data || {};
var str = "";
for(var i in data){
str += `${i}=${data[i]}&`;
}
str = str.slice(0,str.length-1);
var p = new Promise(function(success,error){
var ajax = new XMLHttpRequest();
ajax.open("post",url,true);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
success(ajax.responseText)
}else if(ajax.readyState == 4 && ajax.status != 200){
error(ajax.status)
}
}
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(str);
})
return p;
}
2.3 jsonp
The jsonp place because it is similar to the package and the package, and it can use the script tag to load the external file is not characteristic of the same origin policy restrictions to solve cross-domain problems
function jsonp(url,data){
data = data || {};
var str = "";
for(var i in data){
str += `${i}=${data[i]}&`;
}
var d = new Date();
url = url + "?" + str + "__qft=" + d.getTime();
var p = new Promise(function(success){
var script = document.createElement("script");
script.src = url;
document.body.appendChild(script);
window[data[data.columnName]] = function(res){
success(res)
}
})
return p;
}