Basic Ajax tutorial

Source: Internet
Author: User
Tags tld

What Is Ajax?

Ajax (Asynchronous JavaScript and XML) is a new term designed to describe the powerful performance of JavaScript. these two performances have been ignored by network developers for many years. Until recently, the birth of Gmail, Google suggest, and Google Maps made people begin to realize their importance. the two neglected performances are:

* Requests can be sent to the server without the need to reload the entire page.

* Parse and process XML documents.

Step 1-"Please! "--- How to send an HTTP request

 

To use JavaScript to send an HTTP request to the server, a class instance with this function is required.

This class is first introduced by Internet Explorer as an ActiveX object, known as XMLHTTP. Later, Mozilla, Safari, and other

Browsers follow suit and provide the XMLHttpRequest class, which supports the methods and Attributes provided by Microsoft ActiveX objects.

Therefore, to create a cross-browser class instance (object), you can apply the following code:

If (window. XMLHttpRequest) {// Mozilla, Safari ,...

Http_request = new XMLHttpRequest ();

} Else if (window. activexobject) {// IE

Http_request = new activexobject ("Microsoft. XMLHTTP ");

}

(The code is simplified in the previous example to explain how to create an XMLHTTP class instance.

For actual code examples, see Step 3 .)

Some Mozilla browsers may not work properly if the server response does not contain XML mime-type header.

If the server response header is not text/XML, you can call other methods to modify the header.

Http_request = new XMLHttpRequest ();

Http_request.overridemimetype ('text/xml ');

Next, we need to determine what needs to be done after receiving the response from the server. This requires to tell the HTTP request object which JavaScript function is used.

To process this response, you can set the onreadystatechange attribute of the object to the name of the JavaScript function to be used, as shown below:

Http_request.onreadystatechange = nameofthefunction;

Note: There are no parentheses after the function name and no parameters need to be passed. There is also a way to define the function and its

The actions to be taken in response are as follows:

Http_request.onreadystatechange = function (){

// Do the thing

};

After defining how to handle the response, you need to send the request. You can call the open () and send () Methods of the HTTP request class, as shown below:

Http_request.open ('get', 'HTTP: // www.example.org/some.file', true );

Http_request.send (null );

* The first parameter of open () is the HTTP Request Method-Get, post, Head, or the method you want to call supported by any server.

According to the HTTP specification, this parameter must be capitalized; otherwise, Some browsers (such as Firefox) may not be able to process requests. Details about HTTP request methods

For more information, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html W3C specs

* The second parameter is the URL of the Request page. due to security restrictions, the page cannot be a third-party domain name page.

Make sure that the correct domain name is used on all pages. Otherwise, the error message "Permission denied" is displayed when you call open ().

A common error is that domain. TLD is used to access the website, but www. domain. TLD is used to request the page.

* The third parameter sets whether the request is in asynchronous mode. If it is true, the JavaScript function will continue to be executed without waiting for the server to respond.

This is "A" in "ajax ".

If the first parameter is "Post", the send () method parameter can be any data that you want to send to the server. In this case, the data must be a string.

To the server, as shown below:

Name = Value & anothername = othervalue & so = on

Step 2-"Yes! "--- Process Server Response

When sending a request, you must provide the JavaScript function name specified to process the response.

Http_request.onreadystatechange = nameofthefunction;

Let's take a look at the functions of this function. First, the function will check the Request status. If the status value is 4, it means a complete

The server response has been received and you can process the response.

If (http_request.readystate = 4 ){

// Everything is good, the response is already ed

} Else {

// Still not ready

}

The value of readystate is as follows:

* 0 (not initialized)

* 1 (loading)

* 2 (loaded)

* 3 (in interaction)

* 4 (finished)

(Source)

Then, the function checks the status value of the HTTP server response. For the complete status value, see W3C site. The value is 200.

OK response.

If (http_request.status = 200 ){

// Perfect!

} Else {

// There was a problem with the request,

// For example the response may be a 404 (not found)

// Or 500 (internal server error) Response codes

}

After checking the Request status value and response HTTP status value, you can process the data obtained from the server. There are two methods available:

To get the data:

* Http_request.responsetext-returns the server response in the form of a text string

* Http_request.responsexml-

Return the response as an xmldocument object. Javascript DOM functions can be used to process the xmldocument object.

Step 3-"Everything is ready! "-Simple instance

Now we will complete the entire process and send a simple HTTP request. We use JavaScript to request an HTML file,

Test.html: The text content of the file is "I'm a test.". Then, we use the content of "alert ()" test.html file.

Style = "cursor: pointer; text-Decoration: underline"

Onclick = "makerequest('test.html ')">

Make a request

In this example:

* The user clicks the "request" link in the browser;

* Then the makerequest () function will be called. Its Parameter-HTML file test.html is in the same directory;

* In this way, the execution result of the request. onreadystatechange will be sent to alertcontents ();

* Alertcontents () will check whether the server's response is successfully received. If yes, it will be in the "alert ()" test.html File

Rong.

Step 4-"X-document" --- process XML response

In the previous example, when the server receives the response to the HTTP request, we will call the reponsetext attribute of the request object.

The content of the test.html file is included. Now let's try the responsexml attribute.

First, we create a valid XML file, which will be used later. The source code of this file (test. XML) is as follows:

I'm a test.

 

In this script, we only need to modify the request section:

...

Onclick = "makerequest ('test. xml')">

...

Next, in alertcontents (), we replace alert () code alert (http_request.responsetext);:

VaR xmldoc = http_request.responsexml;

VaR root_node = xmldoc. getelementsbytagname ('root'). Item (0 );

Alert (root_node.firstchild.data );

Here, we use the xmldocument object provided by responsexml and the DOM method to get the content stored in the XML file.

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.