Ajax| Electronic Tutorials
What is AJAX?
AJAX (asynchronous JavaScript and XML) is a new term, designed to describe two powerful features of JavaScript. These two sexual
has been overlooked by web developers for years, until the recent advent of Gmail, Google suggest and Google Maps to make people
are beginning to realize its importance.
These two overlooked properties are:
* Request can be sent to the server without reloading the entire page.
* Parsing and processing of XML documents.
Step "Please!"---how to send an HTTP request
To send an HTTP request to the server with JavaScript, you need a class instance with this functionality.
Such classes are first introduced by Internet Explorer as ActiveX objects, known as XMLHTTP. Later Mozilla, Safari and other
Browsers have emulated, providing a XMLHttpRequest class that supports the methods and properties provided by Microsoft's ActiveX objects.
Therefore, in order 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 previous example simplifies the code to explain how to create an instance of the XMLHTTP class.)
The actual code instance can be read in step 3 of this article.
If the server's response does not have an XML Mime-type header, some Mozilla browsers may not work correctly. To solve this
Problem, if the header of the server response is not text/xml, you can invoke other methods to modify the header.
Http_request = new XMLHttpRequest ();
Http_request.overridemimetype (' Text/xml ');
Next you decide what you need to do when you receive a response from the server. This needs to tell the HTTP request object which JavaScript function to use
Handle this response. You can set the object's onReadyStateChange property to the name of the JavaScript function you want to use, as follows:
Http_request.onreadystatechange = nameofthefunction;
Note: There is no parentheses after the function name, and there is no need to pass arguments. There is another way to define functions in the title page (fly) and their
Respond to the behavior you want to take, as follows:
Http_request.onreadystatechange = function () {
Do the Thing
};
After defining how to handle the response, the request is sent. You can call the open () and send () methods of the HTTP request class, as follows:
Http_request.open (' Get ', ' http://www.example.org/some.file ', true);
Http_request.send (NULL);
* The first parameter of the Open () is the HTTP request method –get, POST, head or any server supported by the way you want to invoke
. This argument is capitalized according to the HTTP specification, otherwise some browsers, such as Firefox, may not be able to process the request. Detailed information about HTTP request methods
Fine information can be referred to the http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html Consortium specs
* The second parameter is the URL of the requesting page. Because of its own security features, this page cannot be a third party domain Name page. At the same time must
To make sure that the exact domain name is used on all pages, calling open () gets the "permission denied" error prompt. A
A common mistake is to use DOMAIN.TLD when you visit a site, but when you request a page, you use WWW.DOMAIN.TLD.
* The third parameter sets whether the request is asynchronous. If true, the JavaScript function will continue to execute without waiting for the server to ring
It should be. This is "A" in "AJAX".
If the first argument is "POST", the parameter of the Send () method can be any data that you want to send to the server. When the data is to be string
To the server as follows:
Name=value&anothername=othervalue&so=on
step 2– "Receive!"---processing server response
When sending a request, provide the name of the JavaScript function that specifies the response to be processed.
Http_request.onreadystatechange = nameofthefunction;
Let's see what the function of this function is. First, the function checks the state of the request. If the status value is 4, it means a complete
The server response has been received and you will be able to handle the response.
if (http_request.readystate = = 4) {
Everything is good, the response is received
} else {
Still not ready
}
The readystate values are as follows:
* 0 (uninitialized)
* 1 (loading)
* 2 (Load complete)
* 3 (Interactive)
* 4 (complete)
(Source)
The function then checks the status value of the HTTP server response. Full state values can be found in the site. We're looking at a value of 200.
OK response.
if (Http_request.status = = 200) {
perfect!
} else {
There was a problem with the request,
For example the "response may" a 404 (Not Found)
or (Internal Server Error) Response codes
}
After checking the status value of the request and the HTTP status value of the response, you can process the data from the server. There are two ways to
To get the data:
* http_request.responsetext– Returns the response of the server as a text string
* http_request.responsexml–
Returns the response as a XmlDocument object. Processing XmlDocument objects can use JavaScript DOM functions
step 3– "Everything is ready!"-simple example
We will now complete the whole process once 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 "alert ()" test.html the contents of the 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 is a problem with the request. ');
}
}
}
</script>
<span
Style= "Cursor:pointer; Text-decoration:underline "
>
Make a request
</span>
In this example:
* User clicks on the "Request" link on the browser;
* Then the function makerequest () is invoked. Its parameter –html file test.html in the same directory;
* This makes a request. onReadyStateChange's execution results will be transmitted to alertcontents ();
* Alertcontents () checks whether the server's response has been successfully received, and if so, the "alert ()" Test.html file
Capacity.
step 4– an "x-document"---process an XML response
In the previous example, when the server's response to the HTTP request was received, we invoked the Reponsetext property of the requesting object. The genus
Sex contains the contents of the test.html file. Now let's try the Responsexml property.
First, we create a valid XML file, which we will use later. The file (test.xml) source code looks like this:
<?xml version= "1.0"?>
<root>
I ' m a test.
</root>
In this script, we just need to modify the request part:
...
>
...
Then, in Alertcontents (), we will alert () Code alert (Http_request.responsetext), and replace with:
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 that is stored in the XML file.
trackback:http://tb.blog.csdn.net/trackback.aspx?postid=599314