A few ways to implement native Ajax in JavaScript introduce _javascript skills

Source: Internet
Author: User

Since JavaScript has a variety of frameworks, such as jquery, using Ajax has become quite simple. But sometimes in order to pursue simplicity, it is possible that the project does not need to load jquery such a large JS plug-in. But what about the ability to use AJAX? Here's a couple of ways to use JavaScript to implement native Ajax.

You must create a XMLHttpRequest object before you implement Ajax. If you do not support the browser that created the object, you need to create ActiveXObject, as follows:

Copy Code code 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:
Copy Code code as follows:

function doget (URL) {
Note that when passing the parameter value, it is best to use encodeURI to deal with it, in case garbled
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:
Copy Code code as follows:

function DoPost (url,data) {
Note that when passing the parameter value, it is best to use encodeURI to deal with it, in case garbled
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.