Always like to use Ajax to do some convenient page small function, but each time to write a lesson plan feel very laborious, so encapsulated a simple Ajax class. After all, is not proficient JS, also hope you pointing twos ~ ~ No nonsense, paste code ~ ~
functionAjax () { This. Request; This. header= "/home/";//Ajax Beginners One of the most easily encountered problems, path problems, must be from the domain after the start of writing ~ ~ is not a relative path is not an absolute path ha This. createrequest=function() { varrequests; if(window. XMLHttpRequest) {Requests=NewXMLHttpRequest (); } Else{Requests=NewActiveXObject ("Microsoft.XMLHTTP"); } returnrequests; } This. send=function(Lujing,val,huidiao)//The first is the path to be connected to the path defined above, the second is the data to post, the object data type, and the third is the callback function{that= This; This. request= This. Createrequest (); This. Request.open ("POST", This. header+lujing+ "? id=" +math.random (),true); This. Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); This. request.onreadystatechange=function() {Huidiao (that.request);//Pass the request as a parameter back to the function, no more global variables}vartxt= This. Objjie (val);//assembles object objects into strings for use by the Send method This. Request.send (TXT); } This. objjie=function(Val)//incoming Val is an object with only key-value pairs, no other composite types { varTxt= ""; for(varIinchval) {txt+=i+ "=" +val[i]+ "&"; } txt=txt.substring (0,txt.length-1); returntxt; }}
Encapsulate Ajax into classes, with convenience