Example of how to implement ajax get and post in original ecological js

Source: Internet
Author: User

With jquery, ajax has become quite simple.
However, for simplicity, you may not need to load a huge js plug-in such as jquery in the project.

But what should I do if I want to use ajax?

Before implementing ajax, you must create an XMLHttpRequest object.
If you cannot create a browser for this object, you need to create ActiveXObject as follows:

Var xmlHttp;
Function createxmlHttpRequest (){
If (window. ActiveXObject ){
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
} Else if (window. XMLHttpRequest ){
XmlHttp = new XMLHttpRequest ();
}

1. Use the xmlHttp created above to implement the simplest ajax get request:

Function doGet (url ){
// Use encodeURI to process parameter values to prevent garbled characters.
CreatexmlHttpRequest ();
XmlHttp. open ("GET", url );
XmlHttp. send (null );
XmlHttp. onreadystatechange = function (){
If (xmlHttp. readyState = 4) & (xmlHttp. status = 200 )){
Alert ('success ');
} Else {
Alert ('fail ');
}
}
}

2. Use the xmlHttp created above to implement the simplest ajax post request:

Function doPost (url, data ){
// Use encodeURI to process parameter values to prevent garbled characters.
CreatexmlHttpRequest ();
XmlHttp. open ("POST", url );
XmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
XmlHttp. send (data );
XmlHttp. onreadystatechange = function (){
If (xmlHttp. readyState = 4) & (xmlHttp. status = 200 )){
Alert ('success ');
} Else {
Alert ('fail ');
}
}
}

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.