Ajax Primer in JavaScript

Source: Internet
Author: User
Tags http request

What is AJAX?

AJAX (Asynchronous JavaScript and XML, asynchronous JavaScript and XML technology) is a new word, but the implication is that two JavaScript features exist for some time. These two functions have been neglected in the past, in Gmail, Google suggest and Google Maps after the emergence of the fame world know.

These two JavaScript features are:

* Send a request to the server without reading the page again (request)
* Parse, use XML file

The first step-how to issue XMLHttpRequest

In order to send HTTP requirements to the server with JavaScript, you must first make the entity (instance) in the relevant category (class). Internet Explorer First provides the XMLHTTP category as an ActiveX object, while Mozilla, Safari, and other browsers then support the categories and attributes in this ActiveX object in the XMLHttpRequest category.

So, if you want to cross browser, you can write this:

The code is as follows Copy Code
if (window. XMLHttpRequest) {//Mozilla, Safari, ...
Http_request = new XMLHttpRequest ();
else if (window. ActiveXObject) {//IE
Http_request = new ActiveXObject ("Microsoft.XMLHTTP");
}

(Since this program is for illustration only, it is the simplest way to write it.) In the third step of this article, there is another kind of writing that we use more often. )

Some versions of Mozilla browsers have errors when the server returns data that does not contain an XML Mime-type file header (header). To avoid this problem, you can overwrite the file headers returned by the server in the following ways, so as not to return the text/xml.

The code is as follows Copy Code
Http_request = new XMLHttpRequest ();
Http_request.overridemimetype (' Text/xml ');

The next step is to determine how the server is going to return the data, at which point you can specify a JavaScript function name to process the return value by using the onReadyStateChange attribute, for example:

The code is as follows Copy Code

Http_request.onreadystatechange = nameofthefunction;

Note that the specified function name has no parentheses and no parameters. In addition to specifying a function name, you can also define a new handler using the Javascript instant definition function, as follows:

The code is as follows Copy Code
Http_request.onreadystatechange = function () {
Do the Thing
};

Once you have decided to process the request, you need to call the open () and send () method in the HTTP request category, as follows:

The code is as follows Copy Code
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, which is chosen from the Get, POST and head, and can be supported on your host. To follow the HTTP standard, remember that these methods are all uppercase, or some browsers (such as Firefox) may not be able to ignore you. For a list of other methods that HTTP request can support, please refer to the WWW specification.
* The second parameter is the destination URL. Based on security considerations, you cannot call a Web page other than the same domain. If the domain is different, the error of "Insufficient permissions, denial of Access" occurs when you call open (). Most of the mistakes that we make are the pages in the DOMAIN.TLD Web site that call Www.111cn.net, just a little bit of difference.
* The third parameter determines whether this request is not synchronized and, if set to TRUE, continues to execute the remainder of the program even if the server has not yet returned the data, which is the meaning of the first A in AJAX.

The parameters of Send () can be anything that you want to pass to the server when you send the request at POST, and the data is listed as a query string, for example:

Name=value&anothername=othervalue&so=on

However, if you want to send data by POST, you must first change the MIME form to the following:

Http_request.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');
Otherwise, the server will not be able to ignore the information you pass over.

Step Two – Process the data returned by the server

The function name that handles the return value must be provided when the request is outgoing.

Http_request.onreadystatechange = nameofthefunction;

So let's take a look at what this function should do. First, it must check the current state of the request: if the status value of 4 indicates that the server has returned all the information, it can begin parsing the resulting information.

The code is as follows Copy Code
if (http_request.readystate = = 4) {
Everything is good, the response is received
} else {
Still not ready
}

ReadyState all possible values are as follows:

* 0 (not yet started)
* 1 (in read)
* 2 (Read)
* 3 (exchange of information)
* 4 (all completed)

Next, check the HTTP status code returned by the server. All status code listings can be found on the Web site, but we're going to be in the state of OK.

The code is as follows Copy Code
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 HTTP status code returned, it is up to you to decide what to do with the returned data. There are two ways to access data:

* http_request.responsetext– This will send back the worth of string
* http_request.responsexml– This will treat the return value as a XmlDocument object, and then use the JavaScript DOM correlation function to process

Step three – everything is ready – simple example

OK, then do a simple HTTP example, demo just the various techniques. This JavaScript will ask the server for an HTML file (test.html) with the words "i ' m a test.", and then list the contents of the file with alert ().

The code is as follows Copy Code

<script type= "Text/javascript" language= "JavaScript" >
function makerequest (URL) {

var http_request = false;

if (window. XMLHttpRequest) {//Mozilla, Safari,...
Http_request = new XMLHttpRequest ();
if (Http_request.overridemimetype) {
Http_request.overridemimetype (' Text/xml ');
Below about this line
}
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 = function () {alertcontents (http_request);};
Http_request.open (' Get ', url, true);
Http_request.send (NULL);

}

function Alertcontents (http_request) {

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 "
onclick= "MakeRequest (' test.html ')" >
Make a request
</span>


In this example:

* First user presses "make a request"
* This will call the MakeRequest () function, also passed the parameter value test.html (that is, the name of the HTML file, placed in the same directory)
* The request is then issued and the dominance is handed over to the onreadystatechange-specified alertcontents () function
* Alertcontents () Check that the response is normal and then alert () lists the contents of the test.html

You can either test this example or refer to the test file.

Step Fourth – Process XML response values

In the previous example, after receiving the HTTP return value we used the contents of the test.html file with the Reponsetext attribute of the object, and then try the method of Responsexml property.

First, we need to make a well-formed XML file so that we can take it later. This file name called Test.xml, the contents are as follows:

The code is as follows Copy Code
<?xml version= "1.0"?>
<root>
I ' m a test.
</root>

In the program, we call the file with a place that only needs to be modified as follows:

...
onclick= "MakeRequest (' Test.xml ')" >
...
Then in Alertcontents (), we have to take alert (http_request.responsetext); Change to this:

The code is as follows Copy Code
var xmldoc = Http_request.responsexml;
var root_node = xmldoc.getelementsbytagname (' root '). Item (0);
alert (root_node.firstChild.data);

This allows us to get the XmlDocument object that Responsexml returns and then fetch the XML file content in a DOM-related way

Test code
Test.xml

The code is as follows Copy Code
<?xml version= "1.0"?>
<root>
I ' m a test.
</root>

Ajax instance with code

The code is as follows Copy Code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en"
"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<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) {
var xmldoc = Http_request.responsexml;
var root_node = xmldoc.getelementsbytagname (' root '). Item (0);
alert (root_node.firstChild.data);
} else {
Alert (' There is a problem with the request. ');
}
}

           }
        </script>
         <body>
        <span
             style= "Cursor:pointer; Text-decoration:underline "
            onclick=" MakeRequest (' Test.xml ') "
                 make a request
        </span>
    </ Body>

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.