Native ajax-encapsulated Ajax

Source: Internet
Author: User
Tags error status code

First, XMLHttpRequest

The core of Ajax technology is the XMLHttpRequest object (abbreviated as XHR), a feature introduced by Microsoft first, and other browser providers later provide the same implementation. Before the advent of XHR, Ajax-style communications had to be implemented by means of a hidden framework or inline framework.

Ajax, is the shorthand for asynchronout javascript+xml. This technology can request additional data from the server without uninstalling/refreshing the page, resulting in a better user experience.

1. Browsers that support native XHR objects create XHR objects that can instantiate XMLHttpRequest directly.

    

  

2. When using a Xhr object, you must first call the open () method, which receives three parameters: the type of request to send (get/post), the URL of the request, and whether the representation is asynchronous (async). The open () method does not actually send the request, but only initiates a request for sending.

3. Send the request via the Send () method, and the Send () method accepts a parameter as the data sent by the request principal. If you do not need to fill in null. After the Send () method is executed, the request is sent to the server.

4. After the request is sent to the server, the response data is automatically populated with the properties of the Xhr object, with a total of four properties:

    

5. After accepting the response, the first step checks the status property to determine that the response has returned successfully, as in the following state code:

    

  

6. Judge the HTTP status value to determine if the response returned successfully

    

7. When using asynchronous invocation, the readyState property is detected and the ReadyStateChange event is triggered whenever the ReadyState property is changed. This property has a total of five values:

    

    

Second, get and post

1. Get request

The server receives the return response data by passing the key value pair data to the server through the question mark after the URL. The problem of special character nginx can be encoded by using encodeuricomponent () , the return of Chinese characters and the parameters, the page can be saved and set to Utf-8, and the data returned by Ajax is UTF-8.

2. Post request

By sending the data of the post request, the data is not followed by the URL, but by the Send () method to the server

      

Sending a POST request to the server due to the parsing mechanism, special processing is required. Because post requests and Web Form submissions are different, you need to use XHR to mimic form submissions.

      

Performance-based post requests consume more than get requests, compared with the same data, get requests up to twice times faster than post requests

Third, encapsulate Ajax

  

<script type= "Text/javascript" >varobj={URL:"User", Method:"POST", Data:{name:"Zs", age:18}, Async:true, Success:function(Result) {Console.log (result); Console.log (Json.parse (Result)}, error:function(Result) {Console.log (result); }}ajax (obj)functionAjax (obj) {//get XMLHttpRequest Object    varXhr=NewXMLHttpRequest (); //to format ParametersObj.data=params (obj.data); //How to determine the request    if(obj.method.toUpperCase () = = "GET") {Obj.url+ = (obj.url.indexOf ("?") ==-1)? "?" +obj.data: "&" +Obj.data; //Open () method: Request mode/Request Path/asynchronousXhr.open (Obj.method,obj.url,obj.async); //Send RequestXhr.send (NULL); }Else{//POST RequestXhr.open (Obj.method,obj.url,obj.async); //Simulate form submissionXhr.setrequestheader ("Content-type", "Application/x-www-form-urlencode"); //Send Requestxhr.send (Obj.data); }    //To determine whether an asynchronous request    if(Obj.async) {//Asynchronous Request        //determine if the response is fully responsiveXhr.onreadystatechange=function(){            if(xhr.readystate==4) {callback (); }        }    }Else{callback (); }        //callback function    functioncallback () {if(xhr.status==200){            //callback functionobj.success (Xhr.responsetext); }Else{obj.error ("The request failed!" Error status Code "+xhr.status+", error Reason "+xhr.statustext); }    }}/** * Converts a JSON-formatted string into a common parameter concatenation*/functionparams (data) {varArr=[]; if(data!=NULL&& Data! = ""){         for(varDinchdata) {Console.log (d+" "+Data[d]); varName=encodeURIComponent (d); varValue=encodeURIComponent (Data[d]); Arr.push (Name+"="+value); }        varParam=arr.join ("&"); returnparam; }    return NULL;}</script>

Synchronous:

Submit a request--wait for the server to process--process finished return this period the client browser can not do things, currently only one thing to do.

Asynchronous:

The request is triggered by the event-server processing (then the browser can still do other things)-and processing is complete. Can do multiple things at the same time

Four, jquery encapsulated Ajax

$.ajax () {}

$.get () {}

$.getjson () {}

$.post () {}

Native ajax-encapsulated Ajax

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.