Previous article write to native JS to replace jquery Some common functions: native JS imitation jquery Some common methods , then, how AJAX implementation? The following is a more complete Ajax ()
function Ajax () {var ajaxdata = {Type:arguments[0].type | | "Get", Url:arguments[0].url | | "", Async:arguments[0].async | | True ", Data:arguments[0].data | | NULL, Datatype:arguments[0].datatype | | "Text", Contenttype:arguments[0].contenttype | | "application/x-www-form-urlencoded", Beforesend:arguments[0].beforesend | | function () {}, success:arguments[0].success | | function () {}, Error:arguments[0].error | |
function () {}} ajaxdata.beforesend () var xhr = Createxmlhttprequest ();
Xhr.responsetype=ajaxdata.datatype;
Xhr.open (Ajaxdata.type,ajaxdata.url,ajaxdata.async);
Xhr.setrequestheader ("Content-type", Ajaxdata.contenttype);
Xhr.send (Convertdata (ajaxdata.data)); Xhr.onreadystatechange = function () {if (xhr.readystate = 4) {if (Xhr.status =) {ajaxdata.su
Ccess (xhr.response)}else{ajaxdata.error ()}}} function Createxmlhttprequest () { if (WindoW.activexobject) {return new ActiveXObject ("Microsoft.XMLHTTP"); else if (window.
XMLHttpRequest) {return new XMLHttpRequest ();
} function Convertdata (data) {if (typeof data = = ' object ') {var convertresult = ' ";
for (var c in data) {convertresult+= c + "=" + Data[c] + "&";
} convertresult=convertresult.substring (0,convertresult.length-1) return convertresult;
}else{return data; }
}
Using the format is similar to jquery's Ajax:
Ajax ({
type: "POST",
URL: "ajax.php",
dataType: "JSON",
data:{"val1": "abc", "Val2": 123, "Val3": "456 "},
Beforesend:function () {
//some js code
},
success:function (msg) {
console.log (msg)
},
error:function () {
console.log ("error")
}
The above is a small series for everyone to bring the original JS to achieve the Ajax method (super Simple) of the entire content, I hope to help you, a lot of support cloud Habitat Community ~