IE5 is the first browser to introduce XHR objects. In IE5, the XHR object is implemented through an ActiveX object in the MSXML library. Therefore, you may encounter three different versions of XHR objects in IE, namely Msxml2.xmlhttp, msxml2.xmlhttp.3.0, and mxsml2.xmlhttp.6.0. To use the XHR object in the MSXML library, you need to write a function like the 18th chapter when you create an XML document, for example:
Version before IE7 function createxhr () {if (typeof arguments.callee.activeXString! = "string") {var versions = ["Msxml2.xmlht tp.6.0 "," msxml2.xmlhttp.3.0 "," MSXML2. " XMLHttp "],i,len;for (i = 0, len = versions.length; i < Len; i++) {try {new ActiveXObject (versions[i]); Arguments.callee. activexstring = Versions[i];break;} catch (ex) {//Skip}}}return new ActiveXObject (arguments.callee.activeXString);}
This function will try to create the latest version of the Xhr object based on the availability of the MSXML library in IE.
ie7+, Firefox, Opera, Chrome, and Safari all support native XHR objects that create XHR objects in these browsers using the XMLHttpRequest constructor as follows.
var xhr = new XMLHttpRequest ();
If you only want to support IE7 and later, you can throw away the previously defined function, and only use the native XHR implementation. However, if you must also support an earlier version of IE, you can add support for native XHR objects in this createxhr () function.
function Createxhr () {if (typeof XMLHttpRequest! = "undefined") {return new XMLHttpRequest ();} else if (typeof Activexobje CT! = "undefined") {if (typeof arguments.callee.activeXString! = "string") {var versions = ["msxml2.xmlhttp.6.0", "MSXML2". xmlhttp.3.0 "," MSXML2. XMLHttp "],i,len;for (i = 0, len = versions.length; i < Len; i++) {try {new ActiveXObject (versions[i]); Arguments.callee. activexstring = Versions[i];break;} catch (ex) {//Skip}}}return new ActiveXObject (arguments.callee.activeXString);} else {throw new Error ("No XHR object available.");}}
Run for a minute
The new code in this function first detects the existence of the native XHR object and returns a new instance of it if it exists. If the native object does not exist, the ActiveX object is detected. If neither of these objects is present, an error is thrown. You can then use the following code to create the XHR object in all browsers.
var xhr = createxhr ();
Because the implementation of XHR in other browsers is compatible with the earliest implementations of IE, the XHR objects created above can be used in all browsers in the same way.
The usage of 21.1.1 XHR
When using a Xhr object, the first method to invoke is open (), which accepts 3 parameters: the type of request to be sent ("get", "post", and so on), the requested URL, and a Boolean value that represents whether the request was sent asynchronously. Here is an example of calling this method.
Xhr.open ("Get", "example.php", false);
This line of code initiates a GET request for example.php. For this line of code, you need to explain two points: first, the URL is relative to the execution code of the current page (you can also use absolute path), and the second is to call the open () method does not really send the request, but just to start a request for sending.
requests can only be sent to URLs that use the same port and protocol in the same domain. If there is any difference between the URL and the page that initiated the request, a security error will be raised.
To send a specific request, you must call the Send () method as follows:
Xhr.open ("Get", "Example.txt", false); Xhr.send (null);
Run for a minute
The Send () method here receives a parameter, which is the data to be sent as the request principal. If you do not need to send data through the request principal, you must pass in NULL, because this parameter is required for some browsers. After calling send (), the request is dispatched to the server.
Because this request is synchronous, the JavaScript code waits for the server to respond before continuing. After the response is received, the data for the response is automatically populated with the properties of the Xhr object, as described in the related properties.
- ResponseText: The text to be returned as the response body.
- Responsexml: If the content type of the response is "text/xml" or "application/xml", this property will hold the XML DOM document containing the response data.
- Status: The HTTP status of the response.
- Description of the Statustext:http status.
After the response is received, the first step is to check the Status property to determine that the response has returned successfully. In general, an HTTP status code of 200 can be used as a success flag. At this point, the content of the ResponseText property is ready, and responsexml should be able to access it if the content type is correct. In addition, a status code of 304 indicates that the requested resource has not been modified and can be used directly from the cached version of the browser, which, of course, means that the response is valid. To ensure that you receive the appropriate response, you should check these two status codes as follows:
Xhr.open ("Get", "Example.txt", false); Xhr.send (null); if (Xhr.status >= && xhr.status <) | | xhr.sta Tus = = 304) {alert (xhr.responsetext);} else {alert ("Request was unsuccessful:" + Xhr.status);}
Run for a minute
Depending on the status code returned, this example may display content returned by the server, or an error message may be displayed. We recommend that readers decide what to do next by detecting status, not relying on statustext, which is less reliable when used across browsers. In addition, the contents of the response body are saved to the ResponseText property regardless of the content type, and the value of the Responsexml property is null for non-XML data.
Some browsers incorrectly report a 204 status code. The ActiveX version of XHR in IE will set 204 to 1223, while the native xhr of IE will normalize 204 to 200. Opera will report a status value of 0 when it gets 204.
It's certainly not a problem to send a sync request like before, but in most cases we still send an asynchronous request in order for JavaScript to continue without waiting for a response. At this point, you can detect the ReadyState property of the Xhr object, which represents the current active phase of the request/response process. The following values are desirable for this property.
- 0: not initialized. The open () method has not been called.
- 1: Start. The open () method has been called, but the Send () method has not been called.
- 2: Send. The Send () method has been called, but the response has not been received.
- 3: Receive. Part of the response data has been received.
- 4: Complete. All the response data has been received and can already be used on the client.
The ReadyStateChange event is triggered whenever the value of the ReadyState property is changed from one value to another. This event can be used to detect the value of readystate after each state change. In general, we are only interested in stages where the readystate value is 4, because all the data is now ready. However, you must specify the onReadyStateChange event handler before calling open () to ensure cross-browser compatibility. Let's look at an example below.
var xhr = createxhr (); xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {if (Xhr.status >= && Xhr.status < 300) | | Xhr.status = = 304) {alert (xhr.responsetext);} else {alert ("Request was unsuccessful:" + Xhr.status);}}; Xhr.open ("Get", "Example.txt", true); Xhr.send (null);
Run for a minute
The code above uses the DOM 0-level method to add event handlers for the XHR object because not all browsers support DOM 2-level methods. Unlike other event handlers, the event object is not passed to the onReadyStateChange event handler; it must be determined by the XHR object itself to determine what to do next.
This example uses the Xhr object in the onReadyStateChange event handler and does not use the This object because of the scope problem of the onReadyStateChange event handler. If the This object is used, there are browsers in which the function execution fails or causes an error to occur. Therefore, the use of actual XHR object instance variables is a more reliable way.
In addition, the abort () method can be called before the response is received to cancel the asynchronous request, as follows:
Xhr.abort ();
When this method is called, the XHR object stops triggering the event, and no longer allows access to any object properties related to the response. After the request is terminated, the XHR object should also be dereferenced. Reusing XHR objects is not recommended due to memory reasons.
21.1.2 HTTP Header information
Each HTTP request and response is provided with the appropriate header information, some of which are useful to the developer, and some are useless. The XHR object also provides a way to manipulate the information for both headers (that is, the request header and the response header). By default, the following header information is also sent while the XHR request is being sent.
- Accept: The type of content that the browser can handle.
- Accept-charset: The character set that the browser can display.
- Accept-encoding: The compression encoding that the browser can handle.
- Accept-language: The language currently set by the browser.
- Connection: The type of connection between the browser and the server.
- Cookie: Any cookie that is set on the current page.
- Host: The domain of the page where the request was made.
- Referer: The URI of the page that issued the request. Note that the HTTP specification incorrectly spelled this header field, and to ensure consistency with the specification, it can only be will wrong. (the correct spelling of this English word should be referrer.) )
- User-agent: The user agent string for the browser.
Although the header information actually sent by different browsers will vary, the above list is basically all the browsers will send. Use the setRequestHeader () method to set the custom request header information. This method takes two parameters: the name of the header field and the value of the header field. To successfully send the request header information, you must call setRequestHeader () before calling the open () method and calling the Send () method, as shown in the following example.
var xhr = createxhr (); xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {if (Xhr.status >= && Xhr.status < 300) | | Xhr.status = = 304) {alert (xhr.responsetext);} else {alert ("Request was unsuccessful:" + Xhr.status);}} Xhr.open ("Get", "example.php", true); Xhr.setrequestheader ("MyHeader", "myvalue"); Xhr.send (null);
Run for a minute
After the server receives this customized header information, it can perform subsequent operations accordingly. We recommend that the reader use a custom header field name, and do not use the field name that the browser sends normally, otherwise it may affect the server's response. Some browsers allow developers to override the default header information, but some browsers do not allow it.
Call the getResponseHeader () method of the Xhr object and pass in the header field name to get the corresponding response header information. The call to the getAllResponseHeaders () method allows you to obtain a long string containing all the header information. Take a look at the following example.
var myheader = Xhr.getresponseheader ("MyHeader"); var allheaders = Xhr.getallresponseheaders ();
On the server side, you can also use the header information to send additional, structured data to the browser. In the absence of custom information, the getAllResponseHeaders () method typically returns multiple lines of text as follows:
Date:sun, 2004 18:04:03 gmtserver:apache/1.3.29 (Unix) Vary:acceptx-powered-by:php/4.3.8connection:closeconten t-type:text/html; Charset=iso-8859-1
This formatted output makes it easy for us to check the names of all the header fields in the response without having to check one field at a to see if they exist.
21.1.3 GET Request
GET is the most common type of request and is most commonly used to query the server for certain information. If necessary, the query string parameter can be appended to the end of the URL to send the information to the server. For XHR, the query string at the end of the URL to the incoming open () method must be correctly encoded.
An error that often occurs with get requests is that there is a problem with the format of the query string. The name and value of each parameter in the query string must be encoded with encodeuricomponent () before it can be placed at the end of the URL, and all name-value pairs must be separated by the number (&), as shown in the following example.
Xhr.open ("Get", "example.php?name1=value1&name2=value2", true);
The following function can assist in adding query string parameters to the end of an existing URL:
function Addurlparam (URL, name, value) {URL + = (Url.indexof ("?") = =-1? "?": "&"), url + = encodeuricomponent (name) + "=" + encodeuricomponent (value); return URL;}
This addurlparam () function accepts three parameters: the URL to which the parameter is to be added, the name of the parameter, and the value of the parameter. This function first checks whether the URL contains a question mark (to determine if a parameter already exists). If not, add a question mark; otherwise, add a number. Then, the parameter name and value are encoded and added to the end of the URL. Finally returns the URL after the parameter was added.
The following is an example of using this function to build a request URL.
var url = "example.php";//Add parameter URL = addurlparam (URL, "name", "Nicholas"), url = addurlparam (URL, "book", "Professional Java Script ");//Initialize Request Xhr.open (" Get ", url, false);
Use the Addurlparam () function here to ensure that the query string is well-formed and reliably used for XHR objects.
21.1.4 POST Request
The use of frequencies second to get is the POST request, which is typically used to send data to the server that should be saved. The POST request should submit the data as the principal of the request, and the GET request is not traditionally the case. The body of a POST request can contain very much data and is not limited in format. You can initialize a POST request by passing in the position of the first parameter of the Open () method, as shown in the following example.
Xhr.open ("Post", "example.php", true);
The second step in sending a POST request is to pass some data to the Send () method. Since XHR was originally designed primarily to handle XML, it was possible to pass in an XML DOM document where the incoming document was serialized and submitted to the server as the request principal. Of course, you can also pass in any string you want to send to the server.
By default, the server does not treat post requests and submit Web forms as a request. Therefore, the server side must have a program to read the raw data sent over and parse out useful parts from it. However, we can use XHR to mimic form submissions by first setting the Content-type header information to application/x-www-form-urlencoded, which is the type of content at the time the form was submitted, followed by creating a string in the appropriate format. The 14th chapter has discussed the format of the POST data in the same format as the query string. If you need to serialize the data for a form in a page and then send it to the server via XHR, you can use the Serialize () function described in chapter 14th to create the string:
function SubmitData () {var xhr = createxhr (); xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {if (Xhr.statu s >= && xhr.status < 300) | | Xhr.status = = 304) {alert (xhr.responsetext);} else {alert ("Request was unsuccessful:" + Xhr.status);}}; Xhr.open ("Post", "postexample.php", true); Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded var form = document.getElementById ("User-info"); Xhr.send (serialize (form));}
Run for a minute
This function can be sent to the server after serializing the data in the form with the id "User-info". The following example PHP file postexample.php can get the submitted data through $_post:
<?phpheader ("Content-type:text/plain"); Echo <<<eofname: {$_post[' user-name ']}email: {$_POST[' User-email ']}eof;? >
If you do not set the Content-type header information, the data sent to the server will not appear in the $_post Super global variable. At this time, to access the same data, you must rely on $http_raw_post_data.
a POST request consumes more resources than a GET request. From a performance standpoint, a GET request can reach up to twice times the speed of a POST request to send the same data meter.
Download the offline version of the tutorial: http://www.shouce.ren/api/view/a/15218
21.1 XMLHttpRequest Object "JavaScript Advanced Programming Third Edition"