Examples of ajax network request encapsulation and ajax Encapsulation
Instance code:
// The encapsulated ajax network request function // obj is an object function AJAX (obj) {// cross-origin request if (obj. dataType = "jsonp ") {// here, callback must be a global variable to ensure that this variable cannot be destroyed when the function disappears. // process the function name (to prevent the function names of multiple network requests from being the same and disordered)) var hehe = "callBack" + "_" + new Date (). getTime () + "_" + String (Math. random ()). replace (". "," "); window [hehe] = obj. success; // create the script tag var SC = document. createElement ("script"); SC. src = obj. url + "? "+" Cb = "+ hehe; console. log (SC. src); document. body. appendChild (SC); document. body. removeChild (SC); return;} // 1. Create the ajax object var ajaxObj = null; if (window. XMLHttpRequest) {ajaxObj = new XMLHttpRequest ();} else {ajaxObj = new ActiveXObject ("Microsoft. XMLHTTP ");} // sets the request type obj. type = obj. type. toUpperCase () | "GET"; // if the request is a get request and parameters need to be passed, splice the parameter if (obj. type = "GET") {var arr = []; // defines an array Used to store objects in the data for (var key in obj. data) {arr. push (key + "=" + obj. data [key]);} // use the & separator array to convert it to a form similar to: name = lxl & age = 18 var str = arr. join ("&"); obj. url = obj. url + "? "+ Str; // dialing ajaxObj. open (obj. type, obj. url, true); // send "name = 123 & age = 18" ajaxObj. send () ;}else {var arr = []; // defines the array used to store the object in the data for (var key in obj. data) {arr. push (key + "=" + obj. data [key]); // console. log (arr);} // use the & separator array to convert it to a form similar to: name = lxl & age = 18 var str = arr. join ("&"); // console. log (str); ajaxObj. open (obj. type, obj. url, true); ajaxObj. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); ajaxObj. send (str);} // listen to ajaxObj. onreadystatechange = function () {if (ajaxObj. readyState = 4) {if (ajaxObj. status> = 200 & ajaxObj. status <300 | ajaxObj. status = 304) {// successfully requested obj. success (ajaxObj. responseText);} else {// request failed obj. error (ajaxObj. status );}}}}
The above example of the ajax network request encapsulation is all the content shared by Alibaba Cloud. I hope you can give us a reference and support the help house.