Five steps for AJAX applications

Source: Internet
Author: User

1. Create an xmlHttpRequest object

If (window. XMLHttpRequest ){
XmlHttp = new XMLHttpRequest ();

If (xmlHttp. overrideMimeType ){
XmlHttp. overrideMimeType ("text/xml ");
}
} Else if (window. ActiveXobject ){
Var activeName = ["MSXML2.XMLHTTP", "Microsoft. XMLHTTP"];
For (var I = 0; I <activeName. length; I ++ ){
Try {
XmlHttp = new ActiveXobject (activeName [I]);
Break;
} Catch (e ){
}
}

}
If (! XmlHttp ){
Alert ("failed to create xmlhttprequest object ");
} Else {

}

2. Set the callback function

XmlHttp. onreadystatechange = callback;

Function callback (){}

3. Use the OPEN method to establish a connection with the server xmlHttp. open ("get", "ajax? Name = "+ name, true)

In this step, pay attention to setting the http Request Method (post/get). If it is POST, pay attention to setting the request header information xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ")

4. send data to the server

XmlHttp. send (null );

If the POST method is used, it is not empty.

5. process different response statuses in the callback function

If (xmlHttp. readyState = 4 ){
// Determine whether the interaction is successful
If (xmlHttp. status = 200 ){
// Obtain the data returned by the server
// Obtain plain text data
Var responseText = xmlHttp. responseText;
Document. getElementById ("info"). innerHTML = responseText;
}
}

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.