1. The following code implements support for native XHR objects:
1 functioncreatexhr () {2 if(typeofxmlhttprequest!= "Undefined"){3 returnnewxmlhttprequest (); 4}Else if(typeofactivexobject!= "Undefined"){5 if(typeofArguments.callee.activexstring!= "string"){6 varversion=["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", "Msxml2.xmlhttp"],i,len;7 for(i=0;len=versons.length;i<len;i++){8 Try{9 NewActiveXObject (Versons[i]);Tenarguments.callee.activexstring=Versons[i]; One Break; A}Catch(ex) { - } - } the } - return NewActiveXObject (arguments.callee.activeXString); -}Else{ - Throw NewError ("No XHR object Available"); + } -}
First check that the native XMLHttpRequest () object exists, and the new instance is returned. If the primitive does not exist, the ActiveX object is detected and an error is thrown if neither of these objects exists.
var xhr=createxhr ();
Xhr.open () accepts three parameters, the type of request to send, the URL of the request, and the Boolean value of the asynchronous send request;
To send a specific request:
Xhr.open ("Get", "Example.txt",false); Xhr.send (null);
The Send () method accepts one parameter for the data sent by the requesting body. You do not need to send data through the request principal, you must pass in NULL
The above request is synchronous, the JavaScript code will wait for the server to continue execution, after receiving the corresponding data will automatically populate the properties of the Xhr object, to ensure that the appropriate corresponding, should check the status code;
if ((xhr.status>=200&&xhr.status<300) | | xhr.status==304) {alert (xhr.responsetext); Else{alert ("Request is not success:" +xhr.status); } }
To detect the ReadyState property of an Xhr object when sending an asynchronous request
var xhr=createxhr (); Xhr.onreadystatechange=function() { if( Xhr.readystate==4) { if(xhr.status>=200&&xhr.status<300) | | | xhr.status==304) {alert (xhr.responsetext); Else{alert ("Request is not success:" +xhr.status); } }}};xhr.open ("Get", "Example.text",true); send (null);
The asynchronous request can be canceled by the Xhr.abort () method before the response is received, and the Xhr object should be dereferenced after the request is terminated.
2. Get requests are used to query the server for certain information, append query string parameters to the end of the URL, and use the following function to add query string parameters to the end of the URL
function Addurlparam (url,name,value) {URL+ = (Url.indexof ("?") ==-1 "?": "&"), url+=encodeurlcomponent (name) + "=" +encodeurlcomponent (value); return URL;}
3. The POST request is used to send data to the server that should be saved.
Learning about Ajax