Create a XMLHttpRequest Object
As with many DOM operations, creating a XHR object also has compatibility issues: IE6 and previous versions use ACTIVEXOBJECT,IE7 and other browsers XMLHttpRequest
Not only does IE6 and its previous versions run XHR as a activexobject, but there are also many versions: Msxml2.xmlhttp and later msxml3.xmlhttp after microsoft.xmlhttp from the beginning
function XHR () {var xhr;try {XHR = new XMLHttpRequest ();} catch (e) {var iexhrvers =["Msxml3.xmlhttp", "Msxml2.xmlhttp", "Microsoft.XMLHTTP"];for (var i=0,len=iexhrvers.length; i< len;i++) {try {xhr = new ActiveXObject (Iexhrvers[i]);} catch (e) {continue;}}} return XHR;}
Using XHR
var xhr = XHR ();//open method creates a new HTTP request and specifies the method, URL, and authentication information (user name/password) for this request Xhr.open ("Get", "test.txt", true);/* The first parameter is the request method, The general use of Get and post methods, similar to the method of the form label The second parameter is the URL of the request the third parameter is whether the request is synchronous or asynchronous, true means that the open method is called asynchronously only passed the argument */xhr.send (null);// The Send method is called after a request is made//and the send parameter is null when a GET method is sent
Executing the above script in a server environment and sending a request to a PHP or ASP script will find that the server-side script is actually executed
PHP script $fp =fopen ("A.txt", "WB"), Fwrite ($fp, "PHP file executed in the background"); fclose ($FP); echo "return content!";
The return content of the above PHP script will not be displayed directly on the page, it must be received by JS via Xhr object.
var xhr = XHR (); Xhr.open ("Get", "test.php", true); Xhr.onreadystatechange = callback;//bind a function on the ReadyStateChange event// When the data is received, the event handler function on the ReadyStateChange event is called xhr.send (null); Functon callback () {// In this there is no use this.readystate this is because IE under the activexobject of the particularity if (xhr.readystate = = 4) {//readystate Indicates the document loading progress, 4 is completed alert ( Xhr.reponsetext);//responsetext property used to get the returned text}}
XHR Object reference ReadyState property returns the status of the current request
- 0 (uninitialized) object has been established but not initialized (the open method has not been called)
- 1 (Initialize) object has been established, the Send method has not been called
- 2 (send data) The Send method has been called, but the current state and HTTP headers are unknown
- 3 (data transfer) received part of the data, because the response and HTTP header is not complete, then through the responsebody and responsetext to obtain some of the data will be error
- 4 (complete) The data is received, at which time the complete response data can be obtained by responsebody and ResponseText
var xhr =xhr (); alert (xhr.readystate);//0xhr.open ("Get", "test.htm", true); alert (xhr.readystate);//1xhr.send (null); Alert (xhr.readystate),//ie will be 4, and FF will be 2//can be monitored by readystatechange event xhr = XHR (); xhr.onreadystatechange = function () { Alert (xhr.readystate),//FF will be 1,2,3,4 in turn, but the last 1//ie will be 1,1,3,4};xhr.open ("Get", "test.txt", true); Xhr.send (null);
As can be seen from the above, for readystate this property, the browser view is not the same, but in fact we only need to know when the status of 4 can be obtained response on the line!
Status returns the HTTP status code for the current request
The Status property returns the HTTP status code for the current request, which is only available when the data is sent and received. The full HTTP status code is as follows:
- Continue the initial request has been accepted, the customer should continue to send the remainder of the request
- 101 Switching Protocols Server translates the client's request to another protocol
- All OK, the answer document for Get and post requests is followed.
- The 201 Created Server has created the document, and the location header gives its URL.
- 202 Accepted has accepted the request, but the processing has not been completed.
- 203 Non-authoritative Information The document has returned normally, but some of the answer headers may be incorrect because a copy of the document is used
- 204 No Content There is no new document, the browser should continue to display the original document. This status code is useful if the user refreshes the page periodically and the servlet can determine that the user's document is new enough.
- 205 Reset content is not new, but the browser should reset what it displays. Used to force the browser to clear form input
- The 206 Partial Content client sends a GET request with a range header that the server has completed
- Multiple Choices customer requested documents can be found in multiple locations that have been listed in the returned document. If the server wants to make a preference, it should be indicated in the location answer header.
- 301 Moved Permanently The document requested by the customer elsewhere, the new URL is given in the location header, and the browser should automatically access the new URL.
- 302 Found is similar to 301, but the new URL should be treated as a temporary replacement, not a permanent.
- 303 See other is similar to 301/302, except that if the original request is the Post,location header the specified redirect target document should be fetched by get
- 304 Not Modified client has buffered documents and issued a conditional request (typically providing a if-modified-since header indicating that the customer only wants to update the document than the specified date). The server tells the customer that the original buffered document can continue to be used.
- 305 Use proxy The document requested by the client should be extracted from the agent server indicated by the location header
- 307 Temporary Redirect and 302 (Found) are the same. Many browsers incorrectly respond to a 302 response for redirection, even if the original request is post, even though it can actually be redirected only if the answer to the POST request is 303. For this reason, HTTP 1.1 has been added in 307 to allow for more cleanup of the region in several status codes: When a 303 response occurs, the browser can follow the redirected get and post requests, and if the 307 answer, the browser can only follow the redirect to the GET request.
- A syntax error has occurred in the request requests.
- 401 Unauthorized customer attempts to access password-protected pages without authorization. A www-authenticate header is included in the answer, and the browser displays the user name/Password dialog box, and then makes a request again after filling in the appropriate authorization header.
- 403 Forbidden resource is not available.
- 404 Not Found Cannot find resource at the specified location
- The 405 method not allowed request methods (GET, POST, HEAD, Delete, PUT, trace, etc.) do not apply to the specified resource.
- 406 not acceptable the specified resource has been found, but its MIME type and the incompatibility specified by the client in the Accpet header
- 407 Proxy authentication Required is similar to 401, which means that the client must be authorized by the proxy server first.
- 408 Request Timeout The customer has not made any requests during the waiting time of the server license. Customers can repeat the same request at a later time.
- 409 Conflict is usually associated with a put request. The request cannot succeed because the request conflicts with the current state of the resource.
- 410 Gone The requested document is no longer available, and the server does not know which address to redirect to. It differs from 404 in that returning 407 means that the document has permanently left the specified location, and 404 indicates that the document is unavailable for unknown reasons.
- 411 Length Required The server cannot process the request unless the client sends a CONTENT-LENGTH header
- 412 Precondition Failed Some of the prerequisites specified in the request header failed
- 413 Request Entity Too Large the size of the target document exceeds the size that the server is currently willing to handle. If the server thinks it can process the request later, it should provide a retry-after header
- 414 Request Uri Too long URI too
- 416 requested range not satisfiable server does not meet the Range header specified by the customer in the request
- The Internal server Error server encountered an unexpected situation and could not complete the customer's request
- The 501 not implemented server does not support the functionality required to implement the request. For example, a customer issues a put request that is not supported by the server
- 502 Bad Gateway server as a gateway or proxy, in order to complete the request to access the next server, but the server returned an illegal response
- 503 Service Unavailable Server failed to answer due to maintenance or heavy load. For example, a servlet might return 503 if the database connection pool is full. A retry-after header can be supplied when the server returns 503
- 504 Gateway Timeout is used by a server acting as a proxy or gateway, indicating that the answer is not available in a timely manner from the remote server
- 505 HTTP version not supported server does not support HTTP versions as specified in the request
In fact, we only need to know when the status is 200 (OK) to read the response on the line!
ResponseText and Responsexml
ResponseText returns the response information as a string. XMLHTTP attempts to decode the response information into a Unicode string, XMLHTTP defaults to encoding the response data as UTF-8, and XMLHTTP can decode any UCS-2 if the data returned by the server is with the BOM (Byte-order Mark) (Big or Little endian) or UCS-4 data. Note that if the server returns an XML document, this property does not handle the encoding declaration in the XML document. You need to use Responsexml to handle it.
Responsexml formats The response information as an XML Document object and returns it. If the response data is not a valid XML document and the property itself does not return Xmldomparseerror, the error message can be obtained through the processed DOMDocument object.
Some other methods of XHR objects
Abort cancels the current request
getAllResponseHeaders gets all HTTP headers for the response each HTTP header name and value is separated by a colon and ends with \ r \ n. This method can be called only when the Send method is complete.
getResponseHeader gets the specified HTTP header from the response message when the Send method succeeds, the method is called. If the document type returned by the server is "Text/xml", this sentence is Xmlhttp.getresponseheader ("Content-type") and the string "Text/xml" is returned. You can use the getAllResponseHeaders method to obtain complete HTTP header information.
setRequestHeader specifies an HTTP header for the request, overwriting it if an HTTP header with this name already exists. This method must be called after the Open method.
Request method
GET Request
JS var xhr = XHR (); Xhr.open ("Get", "test.php?qs=true&username=abc&pwd=123456", true); Xhr.onreadystatechange = function () {if (xhr.readystate==4 && xhr.status ==200) {alert (xhr.responsetext);}}; Xhr.send (NULL); PHP Print_r ($_get);
POST Request
JS var xhr = XHR (); Xhr.open ("Post", "test.php", true); Xhr.onreadystatechange = function () {if (xhr.readystate==4 && xhr.status ==200) {alert (xhr.responsetext);}}; One more step than GET request Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); In addition, the data is sent via the Send method Xhr.send ("qs=true&username=abc&pwd=123456"); PHP header ("Cache-control:no-cache, must-revalidate");//allows the browser not to cache the results print_r ($_post);
Xhr--xmlhttprequest Object