Ajax technology in a detailed

Source: Internet
Author: User
Tags http post

Ajax Technology:Ajax describes a Web application architecture that uses scripting (JS) to manipulate HTTP, and its main feature is the use of scripts to manipulate HTTP and Web servers for data exchange without causing page overloading. The core of Ajax is JS's XMLHttpRequest constructor, which defines the API for manipulating HTTP with scripting. XMLHttpRequest Constructor:each of the objects returned by the new XMLHttpRequest constructor represents a separate request/response pair, and the properties and methods of the object allow you to specify the request details and extract the response data. It is important to note that when you reuse an existing XMLHttpRequest, this terminates any requests that were previously suspended through the object. Case: Creating an HTTP API//The object API returned by this constructor is capable of manipulating HTTP, pleasevar xhr = new XMLHttpRequest (); The open () method of the HTTP API:the next step after creating the HTTP API is to call the open () method. This method has three parameters, parameter one specifies the method of HTTP request, GET, POST, DELETE, HEAD, options and put can be used. Parameter two specifies the URL of the request, but the URL cannot be a cross-domain URL. The parameter three specifies whether the request is asynchronous, true indicates asynchronous, and False indicates synchronization. Case: Call of the Open () method var xhr = new XMLHttpRequest ();    var URL = "lookup.php?name=csh&sex= male &ie=utf-8";  Xhr.open (' GET ', URL, true); onReadyStateChange Event:The next step after invoking the open () method is to listen for the onreadystatechange event, which is used primarily to listen for status codes (the Status property) and return data (ReadyState property) when the request is returned. Call the callback function when the status and ReadyState attributes meet the requirements. ReadyState Properties:the value of the ReadyState property is an integer that specifies the state of the HTTP request. 0 indicates that open () has not yet called 1 to indicate that open () has been called 2 to receive header information 3 to receive the response body 4 to indicate that the response is complete theoretically, each time the ReadyState property change triggers the ReadyStateChange event, But in practice, this event may not be triggered when readystate changes to 0 or 1 o'clock. When the readystate value changes to 4 or the server's response is complete, all browsers trigger the ReadyStateChange event. Status property: The value of the ReadyState property is an integer that specifies the status code for the HTTP. Common HTTP Status code: Http:status 200– Server successfully returned page Http:status 404– requested page does not exist Http:status 503– Service Unavailable case: Monitoring onreadystatechange event var xhr = new XMLHttpRequest ();
Xhr.onreadystatechange = function () {
The //2xx state and the 304 that represents a direct fetch from the cache can be seen as successful, IE (non-native XHR object) setting 204 to 1223,opera will be set to 0 when 204 is obtained
if (xhr.readystate = = 4 && (xhr.status >= && xhr.status <) | | xhr.status = = 304 | | xhr.sta Tus = = 1223 | | Xhr.status = = = 0)) {
Options.callback (Converter[datatype].call (this, Xhr.responsetext, Xhr.responsexml));
}}; The Send () method of the HTTP API:This is the last step of the HTTP request, which calls this method to send the request to the server. Send () has an optional parameter, and the GET request is the data passed to the background when the Null,post requestCase: Call the Send () method var xhr = new XMLHttpRequest ();  Xhr.send (NULL); The setRequestHeader () method of the HTTP API:This method is used to set the HTTP header information. In the case of a POST request, you must set the Content-type property of the HTTP header information to tell the MIME type of the data sent to it by the server. If you call setRequestHeader () multiple times, the new value does not replace the previous old value, instead, the HTTP request will contain multiple copies of the header or the header will specify multiple values. Encoding Request body:The HTTP POST request includes a request body that contains the data that the client has passed to the server, and the request body may be complex, in addition to being a simple text string. In AJAX applications, it is most likely that a JS object is sent to the server (that is, the data is stored in an object and sent directly to the server, which means that the object is the request body). Case: Using the JSON encoding body to initiate an HTTP POST request function Postjson (URL, data, callback) {
var request = new XMLHttpRequest ();
Request.open (' POST ', url);//Send a POST request to the specified URLRequest.onreadystatechange = function () {}; Request.setrequestheader ("Content-type", "Application/json");
Request.send (json.stringify (data));//data object to be converted to JSON type}; Case: Sending a GET request/**
* GET Request
* @param Options "This parameter is an object"
* {url: ' http://www.plateno.com/index.html, data: {name: ' Luke '}, callback:function (data) {}}
*/
function get (options) {
var xhr = new XMLHttpRequest (),
Async = Options.async | | True
try{
//Determine if parameters are passed
var data = ', n = 0, a = ';
if (options.data) {
data = '? ';
for (var name in Options.data) {
n = = 0? A = ': A = ' & ';
n++;
Data + = A + name + ' = ' + encodeURI (Options.data[name])
}
}

//Determine if the cache
var cache = ' & ' + new Data (). GetTime ();           if (!options.cache) {cache = ';} Xhr.open (' Get ', Options.url + data + cache, async);//Set request data
Xhr.send ();//Send request

//Listening request process
Xhr.onreadystatechange = function () {
The //2xx state and the 304 that represents a direct fetch from the cache can be seen as successful, IE (non-native XHR object) setting 204 to 1223,opera will be set to 0 when 204 is obtained
if (xhr.readystate = = 4 && (xhr.status >= && xhr.status <) | | xhr.status = = 304 | | xhr.sta Tus = = 1223 | | Xhr.status = = = 0)) {
Options.callBack.call (This, xhr.responsetext, xhr.responsexml);
}}}catch (e) {throw new Error (' Get request failed ');}} Case: Sending a POST request/**
* POST Request
* @param Options "This parameter is an object"
* {url: ' http://www.plateno.com/index.html ', Data:{name: ' Luke '}, callback:function (data) {}}
*/
function post (options) {
var xhr = new XMLHttpRequest (),
Async = Options.async | | True
try{
//Determine if parameters are passed
var data = ', n = 0, a = ';
if (options.data) {
for (var name in Options.data) {
n = = 0? A = ': A = ' & ';
n++;
Data + = A + name + ' = ' + Options.data[name]
}
}

Xhr.open (' Post ', Options.url, async);//Set request data

Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded; Charset=utf-8");//Set the request header

Xhr.send (data);//Send request

//Listening request process
Xhr.onreadystatechange = function () {
The //2xx state and the 304 that represents a direct fetch from the cache can be seen as successful, IE (non-native XHR object) setting 204 to 1223,opera will be set to 0 when 204 is obtained
if (xhr.readystate = = 4 && (xhr.status >= && xhr.status <) | | xhr.status = = 304 | | xhr.sta Tus = = 1223 | | Xhr.status = = = 0)) {
Options.callback (Converter[datatype].call (this, Xhr.responsetext, Xhr.responsexml));
}
}
}catch (e) {throw new Error (' Post request failed ');}}

Ajax technology in a detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.