First, we need to XHR objects. This is not difficult for us to encapsulate into a function.
var createajax = function () {var xhr = null; try {//ie series Browser xhr = new ActiveXObject ("Microsoft.XMLHTTP");
} catch (E 1) {try {//non ie browser XHR = new XMLHttpRequest ();
} catch (E2) {Window.alert ("Your browser does not support AJAX, please replace!") ");
}
} return xhr;
};
Then we'll write the core function.
var ajax = function (conf) {//initialization//type parameter, optional var type = Conf.type//url parameter, required var url = conf.url;//data parameter optional, only on POST request Need var data = Conf.data; DataType parameter optional var dataType = Conf.datatype; callback function Optional var success = conf.success;
if (type = = null) {//type parameter optional, default to get type = ' get ';
} if (DataType = null) {//datatype parameter optional, default to Text DataType = "text"; ///Create Ajax Engine object var xhr = Createajax (); Open Xhr.open (type, URL, true);
Send if (type = = "Get" | | | type = = "Get") {xhr.send (null); else if (type = = "Post" | | | type = = "Post") {Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded
");
Xhr.send (data); Xhr.onreadystatechange = function () {if (xhr.readystate = 4 && xhr.status =) {if (DataType = = "Text" | |
datatype== ' text ' {if (success!= null) {//Plain Text success (Xhr.responsetext); }}else if (datatype== "xml" | |
datatype== "xml" {if (success!= null) {//Receive XML document success (Xhr.responsexml); }}else if (datatype== "JSON" | | Datatype== "JSON" {if (success!= null) {//convert JSON string to JS Object Success (eval ("+xhr.responsetext+"));
}
}
}
}; };
Finally, explain the use of this function.
Ajax ({type: "post",
URL: "test.jsp",
data: "Name=dipoo&info=good",
dataType: "JSON",
success: function (data) {alert (data.name);}});
The above article with the original JS Ajax simple encapsulation of the example code is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.