Ajax everyone already knows, is in order to realize asynchronous communication, improve the user experience degree, but will many old knowledge (Xml,dom,javascript,html,jquery,css ... ) A new knowledge framework for reintegration. And the XMLHttpRequest object is a heavy one. This blog focuses on the use of this object. Of course, according to the classic five steps to learn, later in practice there are more and better ideas, will be taken out to share.
First, you need to understand the properties and methods of this object first:
|
Property |
Description |
|
ReadyState |
Indicates the state of the XMLHttpRequest object: 0: Uninitialized. The object was created without calling open;
The 1:open method was successfully invoked, but the Sendf method was not invoked;
The 2:send method has been invoked and has not yet begun to accept data;
3: Data is being accepted. HTTP response header information has been accepted, but has not yet received completion;
4: Completion, that is, the response data acceptance completed. |
|
onReadyStateChange |
Event triggers that request state changes (the JavaScript function registered on this property is invoked when the readystate changes). |
|
ResponseText |
Text content for server responses |
|
Responsexml |
The DOM object corresponding to the XML content of the server response |
|
Status |
The HTTP status code returned by the server. 200 means "success", 404 means "Not Found", 500 indicates "server internal error", and so on. |
|
StatusText |
The text information for the server to return status. |
|
Method |
Description |
|
Open (String method,string url,boolean asynch,
String username,string Password) |
Specifies the HTTP method, URL address, or other request information, that interacts with the server side;
Method: Represents HTTP request methods, typically using "get", "POST".
URL: The address of the server that represents the request;
Asynch: Indicates whether asynchronous method is used, true is asynchronous, false is synchronous;
The two username and password represent the username and password respectively, providing the user name and password required by the HTTP authentication mechanism. |
|
Send (content) |
A request is made to the server, and if asynchronous, the method returns immediately.
Content can be specified as null to send no data, and its contents can be DOM objects, input streams, or strings. |
|
setRequestHeader (String header,string Value) |
Sets the value for the specified header header in the HTTP request.
This method is called after the Open method and is typically used in post mode. |
|
getAllResponseHeaders () |
Returns all the response header information that contains HTTP, with the corresponding headers including Content-length,date,uri.
The return value is a string that contains all header information, where each key name and key value are separated by a colon and each group of keys is separated by CR and LF (carriage return plus line breaks). |
|
getResponseHeader (String header) |
Returns the value of the header of the key name specified in the HTTP response header |
|
Abort () |
Stops the current HTTP request. The corresponding XMLHttpRequest object is reset to an uninitialized state. |
The object has a static understanding, know what it looks like, what function, the bottom of which we use it, of course, here I also use five steps to write code to:
First step: Create the Xmlhttpruquest object:
var XMLHttpRequest;
if (window. XMLHttpRequest) {
xmlhttprequest=new XMLHttpRequest ();
if (xmlhttprequest.overridemimetype) {
xmlhttprequest.overridemimetype ("Text/xml");
}
} else if (window. ActiveXObject) {
var activename=["MSXML2. XMLHTTP "," Microsoft.XMLHTTP "];
for (Var i=0;i<activename.length;i++) {
try{
xmlhttprequest=new ActiveXObject (activename[i));
break;
catch (E) {
}
}
}
if (xmlhttprequest==undefined | | xmlhttprequest==null) {
alert (" XMLHttpRequest object creation failed. ");
} else{
this.xmlhttp=xmlhttprequest;
}
Step Two: Register callback method
Xmlhttp.onreadystatechange=callback;
Step three: Set the corresponding parameters for the server interaction
Xmlhttp.open ("Get", "ajax?name=" +username,true);
Fourth step: Set the data sent to the server side, start and server-side interaction
Xmlhttp.send (NULL);
Step Fifth: Determine whether the server-side interaction is complete, and whether the server side returns the correct data
Basic actual conditions write callback functional code function
callback () {
if (xmlhttp.readstate==4) {
//indicates the server's corresponding code is 200; correctly returned data
if (xmlhttp.status==200) {
//plain Text data acceptance method
var Message=xmlhttp.responsetext;
The premise of the use is that the server side needs to set Content-type as Text/xml
//var domxml=xmlhttp.responsexml;
Additional code}}
Through these five steps XMLHttpRequest basically create good, can be used normally, but this is to need very many code, can't write so much every time creation. Of course not, we learn the object-oriented, we will be the same part of the necessary to abstract out, make it a separate class, other direct call can be seen on the internet, feel good writing:
class's build definition, the primary responsibility is to create a new XMLHttpRequest object var myxmlhttprequest=function () {var XMLHttpRequest; if (window.
XMLHttpRequest) {xmlhttprequest=new XMLHttpRequest ();
if (xmlhttprequest.overridemimetype) {xmlhttprequest.overridemimetype ("text/xml"); }}else if (window. ActiveXObject) {var activename=["MSXML2.
XMLHTTP "," Microsoft.XMLHTTP "];
for (Var i=0;i<activename.length;i++) {try{xmlhttprequest=new ActiveXObject (activename[i));
Break }catch (e) {}}} if (XMLHttpRequest = = Undefined | | xmlhttprequest = = null) {alert ("XMLHttpRequest object creation failed ...
");
}else{this.xmlhttp=xmlhttprequest; }//The user sends the request method Myxmlhttprequest.prototype.send=function (method,url,data,callback,failback) {if this.xm
lhttp!=undefined && this.xmlhttp!=null) {method=method.touppercase (); if (MetHod!= "Get" && method!= "post") {Alert ("HTTP request method must be GET or POST!!!");
Return } if (Url==null | | url==undefined) {alert ("HTTP's request address must be set.)
");
return;
} var tempxmlhttp=this.xmlhttp; This.xmlhttp.onreadystatechange=function () {if (tempxmlhttp.readystate==4) {if (TEMXMLHT)
tp.status==200) {var responsetext=temxmlhttp.responsetext;
var responsexml=temxmlhttp.reponsexml;
if (callback==undefined | | callback==null) {alert ("There is no way to handle the correct return of data");
Alert ("Returned data:" + responsetext);
}else{callback (Responsetext,responsexml); }}else{if (failback==undefined | | Failback==null) {AleRT ("There is no set processing method for processing data return failure.)
");
Alert ("HTTP response code: + Tempxmlhttp.status +", text message for response code: "+ tempxmlhttp.statustext);"
}else{failback (Tempxmlhttp.status,tempxmlhttp.statustext); /resolves the cached conversion if (Url.indexof ("?")
>=0) {url=url + "&t=" + (new Date ()). valueof ();
}else{url=url+ "? + +" + (new Date ()). valueof (); //Resolve Cross-domain issues if (Url.indexof ("http://") >=0) {url.replace ("?", "&"
);
Url= "Proxy?url=" +URL;
} this.xmlhttp.open (Method,url,true); If it is POST, you need to set the request header if (method== "POST") {This.xmlhttp.setRequestHeader ("Content-type", "Applicat
Ion/x-www-four-urlencoded "); } this.xmlhttp.send (data); }else{alert ("XMLHttpRequest object creation failed to send data.
");
} myxmlhttprequest.prototype.abort=function () {this.xmlhttp.abort ();
}
}
}
Of course, these need us in practice constantly groping, use, and then summed up their own set of commonly used classes, methods and so on. Of course, XMLHttpRequest also has "browser caching Problem", "Chinese garbled problem", "cross-domain access issues" and so on, because they have not encountered these things, so here to understand first, and later encountered serious research.