function Ajax (obj) {//default parameter var defaults = {type: ' Get ', data: {}, URL: ' # ', DataType: ' Text ', Async:true, success : function (data) {Console.log (data)}}//processing parameter, overriding default parameters when passing parameters, non-delivery using default parameters for (var key in obj) {///to overwrite the input parameters with default data set for update Defaults[key] = Obj[key]; }//1, create XMLHttpRequest object var xhr = null; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else{xhr = new ActiveXObject (' microsoft.xmlhttp ');//compatible with earlier versions of IE}//Convert parameters in object form to parameters in string form/* {username: ' Zhangsan ', ' Password ': 123} converted to username=zhangsan&password=123 */var param = '; for (Var attr in obj.data) {param + = attr + ' = ' + obj.data[attr] + ' & ';} if (param) {//substring (start, end) intercepts the string to remove the last &A mp; symbol param = param.substring (0,param.length-1); }//Processing get request parameters and handling Chinese garbled problem if (Defaults.type = = ' Get ') {Defaults.url + = '? ' + encodeURI (param);}//2, ready to send (set parameters sent) Xhr.open (Defaults.type,defaults.url,defaults.async); Processing the POST request parameters and setting the request header information (must be set) var data = null; if (Defaults.type = = ' Post ') {data = param; Xhr.setrequestheader ("CoNtent-type "," application/x-www-form-urlencoded "); the request header, which must be added in//post mode, is the body part that tells the server how to parse the request. }//3, Perform send action xhr.send (data); Processing a synchronization request does not invoke the callback function if (!defaults.async) {if (Defaults.datatype = = ' json ') {return json.parse (xhr.responsetext);} else{return xhr.responsetext;}} 4. Specify callback function (processing server response data) Xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {//4 Get Data success if (Xhr.status = = 200) {//20 0 obtained data format correctly var data = Xhr.responsetext; if (Defaults.datatype = = ' json ') {//data = eval ("(" + Data + ")"); data = Json.parse (data);//json.parse converts the JSON-formatted information to JS Object form can be used} defaults.success (data);//Callback Function}}}}
JS source code mimics jquery's AJAX acquisition data (Get,post) of the request encapsulation