Basic Ajax tutorial and preliminary use

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:
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

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, called XMLHTTP. later, Mozilla, Safari, and other browsers followed suit and provided 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 the actual code instance, see Step 3 .)

Some Mozilla browsers may not work properly if the server's response does not contain the XML mime-type header. to solve this problem, 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 decide what to do when we receive the response from the server. this tells the HTTP request object which JavaScript function is used to process the 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 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 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 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. 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 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
}

The value of readystate is as follows:
0 (not initialized)
1 (loading)
2 (loaded)
3 (in interaction)
4 (finished)

Then, the function checks the status value of the HTTP server response. For the complete status value, see W3C site. We focus on the response with a value of 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 in the form of a text string
Http_request.responsexml-returns a response in the form of an xmldocument object. You can use the Javascript DOM function 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 the "alert ()" test.html file.

<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 makerequest () function will be called. Its Parameter-htmlfile test.html is in the same directory;
In this way, the execution result of the request. onreadystatechange will be sent to alertcontents ();
Alertcontents () checks whether the server's response is successfully received. If yes, the content of the "alert ()" test.html file is displayed.

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

Contents of the response file. 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:

<? 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')">
...

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.