Basic Ajax tutorial

Source: Internet
Author: User
Tags tld
This article Article It will show you the basic overview of Ajax and show two simple examples to help you easily get on the road.

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:

    • You can send a request to the server without reloading the entire page.
    • Parse and process XML documents.

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

In order to use JavaScript to send an HTTP request to the server, a class instance with this function is required. Such a class is first introduced by Internet Explorer with ActiveX object, which is calledXMLHTTPLater, Mozilla, Safari and other browsers followed suit and providedXMLHttpRequestClass, which supports the methods and Attributes provided by Microsoft ActiveX objects.

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

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 the actual code instance, see Step 3 .)

If the server response does not contain XML mime-type header, some Mozilla browsers may not work properly. To solve this problem, if the server response header is notText/XMLYou can call other methods to modify the header.

 
Http_request = new XMLHttpRequest (); http_request.overridemimetype ('text/xml ');

The next step is to determine what needs to be done after receiving the response from the server. This tells the HTTP request object which JavaScript function is used to process the response.OnreadystatechangeSet the property 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 actions for the response in the response page (FLY), as shown below:

 
Http_request.onreadystatechange = function () {// do the thing };

After defining how to handle the response, you need to send the request. You can call the HTTP request classOpen ()AndSend ()Method:

 
Http_request.open ('get', 'HTTP: // www.example.org/some.file', true); http_request.send (null );
    • Open ()The first parameter is the HTTP Request Method-Get, post, head or the method you want to call supported by any server. according to HTTP specifications, this parameter must be capitalized; otherwise, Some browsers (such as Firefox) may not be able to process requests. for more information about HTTP request methods, 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, this page cannot be a third-party domain name page. make sure that the correct domain name is used on all pages. Otherwise, an error message "Permission denied" is returned when you call open. A common error is the use of domain when accessing the site. TLD, but www. domain. TLD.
    • The third parameter sets whether the request is in asynchronous mode.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 ",Send ()The parameters of the method can be any data that you want to send to the server. The data is sent to the server in the form of a string, 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 checks the Request status. if the status value is 4, it means that a complete 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}

ReadystateThe values are 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.200 OK.

 
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 ways to obtain the data:

    • Http_request.responsetext-Return the server response using a text string
    • Http_request.responsexml-XmldocumentResponse in object mode. ProcessingXmldocumentThe object can use Javascript DOM functions.

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 of the file is "I'm a test.". Then we"Alert ()"Test.htmlFile Content.

<SCRIPT type = "text/JavaScript" Language = "JavaScript"> var http_request = false; function makerequest (URL) {http_request = false; If (window. XMLHttpRequest) {// Mozilla, Safari ,... http_request = new XMLHttpRequest (); If (http_request.overridemimetype) {http_request.overridemimetype ('text/xml');} else if (window. activexobject) {// Ie try {http_request = new activexobject ("msxml2.xmlhttp ");} Catch (e) {try {http_request = new activexobject ("Microsoft. XMLHTTP");} catch (e) {}} if (! Http_request) {alert ('Giving up :( cannot create an XMLHTTP instance'); Return false;} http_request.onreadystatechange = alertcontents; http_request.open ('get', URL, true ); http_request.send (null);} function alertcontents () {If (http_request.readystate = 4) {If (http_request.status = 200) {alert (http_request.responsetext );} else {alert ('There was a problem with the request. ') ;}}</SCRIPT> <span style = "cursor: pointer; text-Decoration: underline" onclick = "makerequest('test.html')"> make a request </span>

In this example:

    • Click the "request" link in the browser;
    • Then the FunctionMakerequest ()Will be called. Its Parameter-HTML fileTest.htmlIn the same directory;
    • In this way, a request is initiated.OnreadystatechangeWill be sentAlertcontents ();
    • Alertcontents ()Check whether the server response is successfully received. If yes"Alert ()"Test.htmlFile Content.

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

In the previous example, when the server's response to the HTTP request is received, we callReponsetextProperty. This property containsTest.htmlFile Content. Now let's tryResponsexmlAttribute.

First, create a valid XML file. This file (test. XML) will be used later)Source codeAs follows:

 
<? XML version = "1.0"?> <Root> I'm a test. </root>

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

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

ThenAlertcontents (), We willAlert ()CodeAlert (http_request.responsetext );Replace:

 
VaR xmldoc = http_request.responsexml; var root_node = xmldoc. getelementsbytagname ('root'). Item (0); alert (root_node.firstchild.data );
 
Here, we useResponsexmlProvidedXmldocumentThe object uses the DOM method to obtain 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.