Example Analysis of ajax Network request Encapsulation
This article mainly shows you the "sample analysis of ajax network request encapsulation", which is easy to understand and clear. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of ajax network request encapsulation".
Example code:
/ / encapsulated ajax network request function / / obj is an object function AJAX (obj) {/ / Cross-domain request if (obj.dataType = = "jsonp") {/ / where callback must be a global variable to ensure that this variable cannot be destroyed when the function disappears. / / handle the function name (to prevent multiple network request function names from being confused with the same name Case) var hehe = "callBack" + "_" + new Date (). GetTime () + "_" + String (Math.random ()). Replace ("." ") Window [hehe] = obj.success; / / create 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 ajax object var ajaxObj = null If (window.XMLHttpRequest) {ajaxObj = new XMLHttpRequest ();} else {ajaxObj = new ActiveXObject ("Microsoft.XMLHTTP");} / / set the type of request obj.type = obj.type.toUpperCase () | | "GET"; / / if it is a get request and parameters need to be passed, you need to give url the splicing parameter if (obj.type = = "GET") {var arr = [] / / define an array to store objects in the data for (var key in obj.data) {arr.push (key + "=" + obj.data [key]);} / / separate the array with & to convert it to something similar: name=lxl&age=18 in the form var str = arr.join ("&"); obj.url = obj.url + "?" + str / / dial ajaxObj.open (obj.type,obj.url,true); / / send "name=123&age=18" ajaxObj.send ();} else {var arr = []; / / define an array to store objects in data for (var key in obj.data) {arr.push (key + "=" + obj.data [key]); / / console.log (arr) } / / separate the array with & to convert it to something similar: name=lxl&age=18 in the form 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 ajaxObj.onreadystatechange = function () {if (ajaxObj.readyState = = 4) {if (ajaxObj.status > = 200 & & ajaxObj.status < 300 | | ajaxObj.status = = 304) {/ / request succeeded obj.success (ajaxObj.responseText);} else {/ / request failed obj.error (ajaxObj.status) The above is all the contents of the article "sample Analysis of ajax Network request Encapsulation". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!