First for everyone to share the original JavaScript implementation of AJAX code for your reference, the specific content as follows
var getxmlhttprequest = function () {
if window. XMLHttpRequest) {
//main browser provides XMLHttpRequest object return
new XMLHttpRequest ();
} else if (window. ActiveXObject) {
//low version of IE browser does not provide XMLHttpRequest object
//So must use IE browser specific implementation activexobject return
new ActiveXObject ("Microsoft.xmlhttprequest");
}
;
var xhr = Getxmlhttprequest ();
Xhr.onreadystatechange = function () {
console.log (xhr.readystate);
if (xhr.readystate = = 3 && Xhr.status = =) {
//Get successful Execute Operation
//data in Xhr.responsetext
Console.log (Xhr.responsetext);
}
;
Xhr.open ("Get", "data.php", true);
Xhr.send ("");
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:
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) {
//Note the best use of encodeURI when passing parameter values to prevent garbled
createxmlhttprequest ();
Xmlhttp.open ("get", url);
Xmlhttp.send (null);
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = 4) && (Xmlhttp.status =)) {
A Lert (' success ');
} else {
alert (' fail ');
}
}
(2) Use the XMLHTTP created above to implement the simplest Ajax POST request:
function DoPost (url,data) {
//Note the best use of encodeURI when passing parameter values to prevent 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 =) {
Ale RT (' success ');
} else {
alert (' Fail ');}}}
The above is the entire content of this article, I hope to help you learn.