JavaScript Ajax: Getting started with native Ajax

Source: Internet
Author: User
Tags event listener xml dom document

Background

Traditional Web applications allow the user to fill out a form (form) and send a request to the Web server when the form is submitted. The server receives and processes the incoming form and then sends it back to a new webpage, but it wastes a lot of bandwidth because most of the HTML code in the front and rear two pages is often the same. Since each application communication requires a request to the server, the response time of the application depends on the response time of the server. This causes the user interface to respond much more slowly than the native application.

February 18, 2005, a big guy named Jesse James Garrett (Jessi James Jarrett), published an article called "Ajax:a New Approach to WEB applications", introduced a technology called Asynchronous JavaScript and XML, this technology can request additional data from the server without reloading the page, so that you can partially request the data without having to refresh the entire page, not only saving a lot of bandwidth, but also speeding up the response speed.

--excerpt from Wikipedia and slightly modified

Xhr

XHR full name is XMLHttpRequest, extensible Hypertext Transfer request, is an API, it through the URL on the client and the server to transfer data without the need to make the page refresh, provides complete access to the HTTP protocol, is the core object of Ajax technology, The request process for Ajax can be divided into four parts:

1 Create XMLHttpRequest Object 2 Connect background server 3 Send data request 4 receive server response data;

The XHR object was first introduced in IE5, and the object was implemented through an ActiveX object in the MSXML library. Thus, IE may encounter three different versions of XHR objects: Msxml2.xmlhttp, MSXML2. xmlhttp.3.0, MSXML2. xmlhttp.6.0. Native XHR objects are supported by ie7+, Firefox, Opera, Chrome, and Safari.

First, create XMLHttpRequest object

If you want to be compatible with browsers before IE7, to write functions based on different XHR versions, create ActiveXObject objects, and other browsers, you can create XMLHttpRequest objects directly. The code is as follows:

1 function createxhr () {2     if (typeof XMLHttpRequest! = "undefined") {3         return new XMLHttpRequest (); 4     } else I  F (typeof ActiveXObject! = "undefined") {5         if (typeof arguments.callee.activeXString! = "string") {6             var versions = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", 7                     "Msxml2.xmlhttp"], 8                 i, Len; 9 for             (i=0,len= Versions.length; i < Len; i++) {Ten                 try {One                     new ActiveXObject (Versions[i]);                     arguments.callee.activeXString = versions[i];13                     break;14                 } catch (ex) {                     //skip                 }17             }18         }19         return new ActiveXObject (arguments.callee.activeXString ), or     else {$         throw new Error ("No XHR object available.");     }23}24 var xhr = createxhr ();

However, very few people now want to be compatible with the previous version of IE7, so it can be simplified as follows:

var xhr = new XMLHttpRequest ();
Second, connect the server and send data

XMLHttpRequest connecting to a server is not difficult:

Xhr.open (method, URL, async, user, password)

Using the Open method above to initialize a request, the parameters of the Open method are described below:

Method : The HTTP methods used by the request; such as "GET", "POST", "PUT", "DELETE" and so on. If the next parameter is a non-HTTP (S) URL, the parameter is ignored. URL: The URL to be accessed by this request isasync: An optional Boolean parameter, which defaults to true, meaning whether to perform an asynchronous operation, and if the value is False, the Send () method does not return anything. Until the server's return data has been accepted. If the value is true, a transparent notification to the developer is sent to the relevant event listener. This value must be true if the multipart property is true, otherwise an unexpected event will occur. User : username, optional parameter, for authorization, default parameter is empty string. Password: password, optional parameter, for authorization, default parameter is empty string.

The most common request types in method methods are get and post, typically:

1. Get is used to query the server for some information, while post sends the data to the server to be saved. 2. Get appends the query string parameter to the end of the URL to the server, and post sends the data to the Send () method by passing parameters.

Give me a chestnut:

1 if (method = = "Get") {2             xhr.open ("get", url + "?" + params, true); 3             xhr.send (null); 4         } else if (method = = "Post") {5             Xhr.open ("post", url, True); 6             //Set Content Type 7             xhr.setrequestheader ("Content-type" for form submission), " Application/x-www-form-urlencoded "); 8             xhr.send (params); 9         }

As shown above, the GET request is added directly after the URL? +parm_name=parm_value& To pass the data, and then Xhr.send (null) (NOTE: null cannot be omitted)

Http://www.yourhost.com?username= "myname" &password= "123"

The POST request is a mock-up of the form submission , sets the header information to the content type when the form was submitted, and then passes the params as a parameter to the Send () method to the server.

Third, the response data of the receiving server

After the Send () method is called, the request is dispatched to the server, and the server responds after the request is processed. It is then automatically populated into the properties of the Xhr object.

ResponseText: The text to be returned as the response body. Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the XML DOM document containing the response data. Status: The HTTP status of the response. Description of the Statustext:http status.

We can get the current response state based on the ReadyState property in the Xhr object:

0: not initialized. The open () method has not been called. 1: Start. The open () method has been called, but the Send () method has not been called. 2: Send. The Send () method has been called, but the response has not been received. 3: Receive. Part of the response data has been received. 4: Complete. All the response data has been received and can already be used on the client.

In general, we are only interested in the status "4", and readyState each change will trigger a ReadyStateChange listener event, so we can judge the success of the response by judging readyState in the listener function, and obtain the response data.

Xhr.onreadystatechange = function () {    if (xhr.readystate = = 4) {        //200-300 means successful return, 304 means the resource has not been modified        if ( Xhr.status >= && xhr.status < 300) | | Xhr.status = = 304) {            //Here The response data is processed (save, print, etc.)            Console.log (Xhr.responsetext);        } else {            alert ("Request Was unsuccessful: "+ Xhr.status);}}    ;

At this point, a complete Ajax request is complete:

 1//Create 2 var xhr = CREATEXHR (); 3//Listening status, processing data 4 Xhr.onreadystatechange = function () {5 if (xhr.readystate = = 4) {6 if ((Xhr.status >= 200 & amp;& xhr.status < 300) | | Xhr.status = = 304) {7//processing of xhr.responsetext response data; 8} else {9 alert ("Request was Unsucce Ssful: "+ xhr.status); 10}11}12};13//Connect to Xhr.open (" Get ","/xxx/xxx?param1=value1&param2=value2 ", True ); 15//Send xhr.send (null); + function createxhr () {if (typeof XMLHttpRequest! = "undefined") {return n EW XMLHttpRequest (); +} else if (typeof activexobject! = "undefined") {if (typeof Arguments.callee.activeXS Tring = "string") {versions = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", "MSXM" L2.xmlhttp "],25 I, len;26 for (i=0,len=versions.length; i < Len; i++) {TR                    y {activexobject new (versions[i]); 29 arguments.callee.activeXString = versions[i];30 break;31} catch (ex) {32         }33}34}35 return new ActiveXObject (arguments.callee.activeXString); +} else {37 throw new Error ("No XHR object available."); 38}39}

Resources:

1, XMLHTTPREQUEST-MDN

2. Advanced programming of JavaScript (third edition)

JavaScript Ajax: Getting started with native Ajax

Related Article

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.