Address: http://hi.baidu.com/zhangqiuxi/blog/item/3d0206a84bbd72bbcb130cab.html
This article describes the basics of Ajax-related technologies and provides examples for you to get started.
Step 1-Say "please" (also known as "How to issue XMLHttpRequest 」)
To send HTTP requests to the server using JavaScript, you must first generate an object (Instance) based on the relevant class ). Internet Explorer first provides the XMLHTTP class as an ActiveX object, while Mozilla, Safari, and other browsers subsequently support the classes and attributes in the XMLHttpRequest class.
Therefore, if you want to use a different browser, you can write as follows:
If (window. XMLHttpRequest) {// Mozilla, Safari ,...
Http_request = new XMLHttpRequest ();
} Else if (window. activexobject) {// IE
Http_request = new activexobject ("Microsoft. XMLHTTP ");
}
(This program is only for illustration, so it is written in the simplest way. In the third step, there is another common method .)
Some versions of Mozilla browsers may encounter errors when the data sent back by the server does not contain the XML mime-Type Header (header. To avoid this problem, you can overwrite the file headers sent by the server using the following methods to avoid text/XML being returned.
Http_request = new XMLHttpRequest ();
Http_request.overridemimetype ('text/xml ');
Next, you need to determine the processing method after the server sends data back. At this time, you only need to specify the JavaScript function name for processing the returned value by using the onreadystatechange attribute. For example:
Http_request.onreadystatechange = nameofthefunction;
Note that the specified function name is not followed by parentheses and there is no parameter. In addition to specifying the function name, you can also define a new function using JavaScript in real time, as shown below:
Http_request.onreadystatechange = function (){
// Do something
};
After determining the processing method, you must indeed send a request. In this case, you need to use the open () and send () Methods of the HTTP request type as follows:
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, that is, you can choose to use it from get, post, and head. It can also be supported on your host. To comply with the HTTP standard, please remember that these methods are in uppercase, otherwise Some browsers (such as Firefox) may not care about you. For a list of methods supported by other HTTP requests, see W3C specifications (http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html ).
* The second parameter is the target URL. For security reasons, you cannot use webpages other than the same domain. If the domain is different, an error such as "Access denied due to insufficient Permissions" will occur when open () is used. Generally, most of the errors that people make are called webpage in www. domain. TLD on the website of domain. TLD. The difference is only a little bit.
* The third parameter determines whether the request has different rows. If it is set to true, the server will continue to execute other programs even if the server has not returned data, this is the meaning of the first expression A in Ajax.
The send () parameter can be anything you want to send to the server when post sends a request, and the data is listed as a query string, for example:
Name = Value & anothername = othervalue & so = on
However, if you want to transmit data in post mode, you must first change the MIME type, as shown below:
Http_request.setrequestheader ('content-type', 'application/X-WWW-form-urlencoded ');
Otherwise, the server will not be able to handle the data you have transmitted.
Step 2-"Let's go !」 (Also known as "processing data returned by the server 」)
When sending a request, you must provide the function name for processing the returned value.
Http_request.onreadystatechange = nameofthefunction;
Let's take a look at what this function should do. First, it must check the current status of the request: If the status value is 4, the server has returned all information, you can start parsing the obtained information.
If (http_request.readystate = 4 ){
// Everything is OK, continue Parsing
} Else {
// Not completed yet
}
All possible values of readystate are as follows:
* 0 (not started yet)
* 1 (reading)
* 2 (read)
* 3 (information exchange)
* 4 (everything is done)
Next, check the HTTP status code returned by the server. The list of all status codes can be found on the W3C website, but we need to handle the status of 200 OK.
If (http_request.status = 200 ){
// Everything is ready
} Else {
// It seems a bit problematic. Maybe the server returns 404 (this page is not found) or 500 (internal error) or something.
}
After you check the returned HTTP status code, it is up to you to decide how to process the returned data. There are two ways to access data:
* Http_request.responsetext-this will use the returned value as a string
* Http_request.responsexml-the returned value is treated as an xmldocument object and can be processed using Javascript DOM-related functions.
Step 3-everything-simple example
Well, let's take a simple HTTP example to demonstrate the skills that have just been done. This section of JavaScript will ask the server for an HTML file (test.html) containing "I'm a test." And then list the file content with alert.
<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:
* First, the user presses "make a request 」
* In this way, the makerequest () function is called, and the parameter value test.html (that is, the name of the HTML file, which is stored in the same directory) is passed in)
* Then, the request is sent, and the dominant permission is handed over to the alertcontents () function specified by onreadystatechange.
* Alertcontents () checks whether the response is normal, and then lists the content of test.html with alert ().
You can test this example (http://www.w3clubs.com/mozdev/httprequest_test.html) from this, or refer to the test file (http://www.w3clubs.com/mozdev/test.html ).
Step 4-"X file" (also known as "processing XML response values 」)
In the previous example, after receiving the HTTP return value, we use the content of the test.html file with the reponsetext attribute of the object, and then try the responsexml attribute method.
First, we need to make an XML file in the correct format for later use. This example is named test. xml. The content is as follows:
<? XML version = "1.0"?>
<Root>
I'm a test.
</Root>
In the program, we only need to modify the file as follows:
...
Onclick = "makerequest ('test. xml')">
...
Then in alertcontents (), we must change alert (http_request.responsetext); to the following:
VaR xmldoc = http_request.responsexml;
VaR root_node = xmldoc. getelementsbytagname ('root'). Item (0 );
Alert (root_node.firstchild.data );
In this way, we can get the xmldocument object returned by responsexml, and then use dom-related methods to get the content of the XML file.
This article is the Ajax: Getting Started of Mozilla Developer Center.
(Http://developer.mozilla.org/en/docs/AJAX:Getting_Started) translation. The author of the original article and the compilation history can be in its history page (http://developer.mozilla.org/en/docs/index.php? Title = Ajax: getting_started & Action = history.