Calling Ajax
1<script type= "Text/javascript" src= "Ajax.js" ></script>2<script type= "Text/javascript" >3 //call the wrapped Ajax method4 Ajax ({5Method: "Get",6URL: "get.php",7Asyn:true,8Data: "user=zym&password=1234",9Fn:function(res) {Ten Console.log (res); One } A }); -</script>
Packaged Ajax method functions:
1 functionAjax (Myjson) {2 //New Ajax Object3 varXHR =NULL;4Window. XMLHttpRequest? (xhr=NewXMLHttpRequest ()):(xhr=NewActiveXObject ("Microsoft.XMLHTTP"));5 //define the data transfer method "get" or "post", if not written, then the default is to use "get" Method! 6 varmethod = Myjson.method| | " Get;7 //define the address of the data transfer! 8 varURL =Myjson.url;9 //defines how the data is loaded (synchronous or asynchronous), by default, using Ajax, which is loaded asynchronously! Ten varAsyn = myjson.asyn| |true; One //define the specific data for the transfer! A vardata =Myjson.data; - //the way to execute after success! - varfn =Myjson.fn; the //The first case: If the Get method is used and data is present, it executes: - if(method== "Get" &&data) { -Xhr.open (method,url+ "?") +data+ "&" +math.random (), Asyn); - } + //The second case: If the Post method is used, and data is present, it executes: - if(method== "POST" &&data) { + Xhr.open (Method,url,asyn); AXhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); at xhr.send (data); -}Else{ - xhr.send (); - } - //after the data transfer is successful -Xhr.onreadystatechange=function(){ in if(xhr.readystate==4){ - if(xhr.status>=200&&xhr.status<300){ to fn (xhr.responsetext); +}Else{ -Alert ("Program Error! "); the } * } $ }Panax Notoginseng}
Native JavaScript wrapper an Ajax method