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 ');
}
}
}