//using native JS to encapsulate Ajax//compatible with XHR objectsfunctioncreatexhr () {if(typeofXMLHttpRequest! = "undefined") {//non-IE6 browser return NewXMLHttpRequest (); }Else if(typeofActiveXObject! = "undefined") {//IE6 Browser varVersion = [ "msxml2.xmlhttp.6.0", "Msxml2.xmlhttp.3.0", "Msxml2.xmlhttp", ]; for(vari = 0; i < version.length; i++){ Try{ return NewActiveXObject (Version[i]); }Catch(e) {//Skip over } } }Else{ Throw NewError ("Your system or browser does not support XHR objects! "); }}//Escape Characterfunctionparams (data) {vararr = []; for(varIinchdata) {Arr.push (encodeURIComponent (i)+ "=" +encodeURIComponent (Data[i])); } returnArr.join ("&");}//Encapsulating AjaxfunctionGa_ajax (obj) {varXHR =createxhr (); Obj.url= Obj.url + "? rand=" + math.random ();//Clear CacheObj.data = params (obj.data);//Escape String if(Obj.method = = = "Get") {//determine whether a Get method is used to sendObj.url + = Obj.url.indexOf ("?") = = "-1"? "?" + Obj.data: "&" +Obj.data; } //Asynchronous if(Obj.async = = =true){ //need to trigger onReadyStateChange event when asynchronousXhr.onreadystatechange =function(){ //execution Complete if(Xhr.readystate = = 4) {callBack (); }}} Xhr.open (Obj.method,obj.url,obj.async); //false is synchronous true is asynchronous//"demo.php?rand=" +math.random () + "&name=ga&ga", if(Obj.method = = = "POST") {Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xhr.send (Obj.data); }Else{xhr.send (NULL); } //Xhr.abort ();//Cancel Asynchronous request //Sync if(Obj.async = = =false) {callBack (); } //Return Data functionCallBack () {//determine whether to return the correct if(Xhr.status = = 200) {obj.success (xhr.responsetext); }Else{obj. Error ("Failed to get data, error code:" +xhr.status+ "error message:" +xhr.statustext); } }}varhtml = document.getelementsbytagname ("html") [0];html.onclick=function() {Ga_ajax ({"Method": "Post", "url": "Demo.php", "Data" : { "Name": "Gao", "Age": 100, "num": "12346&598" }, "Success":function(data) {alert (data); }, "Error":function(text) {alert (text); }, "Async":false });}
Write Ajax using native JS