What is the XMLHttpRequest object?
- Creating an XMLHttpRequest object.
- Specifying and submitting your HTTP request to a web server.
- Synchronously or asynchronously retrieving the server's response.
Propertie Name | Description |
---|---|
onreadystatechange | An event handler for an event that fires at every state change. |
readyState |
The readyState property defines the current state of the XMLHttpRequest object.
State Description
readyState = 0 after you have created the XMLHttpRequest object, but before you have called the open() method. |
responseText | Returns the response as a string. |
responseXML | Returns the response as XML, which can be examined and parsed using W3C DOM node tree methods and properties. This property returns an XML document object, when the Content-Type header specifies the MIME(media) type as text/xml, application/xml, or ends in +xml. If the Content-Type header does not contain one of these media types, the responseXML value is null. |
status | Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK"). |
statusText | Returns the status as a string (e.g. "Not Found" or "OK"). |
Method Name | Description |
---|---|
abort() | Cancel the current request. |
getAllResponseHeaders() | The getAllResponseHeaders() method returns all the response headers as a single string with each header on a separate line. The method returns null if readyState value is not 3 or 4. |
getResponseHeader(DOMString header) | Returns the value of the specified HTTP header. Call getResponseHeader() only when the readyState value is 3 or 4 (in other words, after the response headers are available); otherwise, the method returns an empty string. |
open(DOMString method, DOMString url, boolean async, DOMString username, DOMString password) |
Specify the method, url, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible. The async parameter specifies whether the request should be handled asynchronously or not. "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing. |
send() |
After preparing a request by calling the open() method, you send the request to the server. You may call send() only when the readyState value is 1, otherwise the XMLHttpRequest object raises an exception. The request gets sent to the server using the parameters supplied to the open() method. The send() method returns immediately when the async parameter is true, letting other client script processing continue. The XMLHttpRequest object sets the readyState value to 2 (Sent) after the send() method has been called. When the server responds, before receiving the message body, if any, the XMLHttpRequest object sets readState to 3 (Receiving). When the request has completed loading it sets readyState to 4 (Loaded). For a request of type HEAD, it sets the readyState value to 4 immediately after setting it to 3. The send() method takes an optional parameter that may contain data of varying types. Typically, you use this to send data to the server using the POST method. You can explicitly invoke the send() method with null, which is the same as invoking it with no argument. For most other data types, set the Content-Type header using the setReuqestHeader() method before invoking the send() method. If the data parameter in the send(data) method is of type DOMString, encode the data as UTF-8. If data is of type Document, serialize the data using the encoding specified by data.xmlEncoding, if supported or UTF-8 otherwise. |
setRequestHeader(DOMString header, DOMString value) | The setRequestHeader() method sets request headers. You may call this method after calling the open() method when the readyState value is 1; otherwise you will get an exception. |
Create an XMLHttpRequest Object
- function createHttpRequest() {
- var httpRequest = null;
- if (window.ActiveXObject) { // For IE6 and below
- httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
- } else { // For IE7 and Modern Browsers
- httpRequest = new XMLHttpRequest();
- }
- return httpRequest;
- }
Submit a Request
- XMLHttpRequest.open("GET", url, true);
If you pass false as the third argument to open(), the send() method is synchronous: it blocks and does not return until the server's response has arrived. Asynchronous responses are generally preferred.
HTTP GET
- var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
- xmlHttpRequest.onreadystatechange = function() {
- }
- xmlHttpRequest.open("GET", "query.php?username=vivian", false);
- xmlHttpRequest.send(null);
HTTP POST
- var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
- xmlHttpRequest.onreadystatechange = function() {
- }
- xmlHttpRequest.open("POST", "query.php", false);
- xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xmlHttpRequest.send("username=vivian");
With POST requests, data is passed to the server in the body of the request, rather than encoding it into the URL itself. Since request parameters are encoded into the URL of a GET request, the GET method is suitable only when the request has no side effects on the server -- that is, when repeated GET requests for the same URL with the same parameters can be expected to return the same result. When there are side effects to a request (such as when the server stores some of the parameters in a database), a POST request should be used instead.
Escape the Data
- var HTTPUTILITY = {
- encodeFormData: function(data) {
- if (!data) {
- return;
- }
- var pairs = [];
- var regexp = /%20/g; // A regular expression to match an encoded space.
- for (var name in data) {
- // Create a name/value pair, but encode name and value first. The global function encodeURIComponent does almost what we want,
- // but it encodes spaces as %20 instead of as "+". We have to fix that with String.replace().
- var value = data[name].toString();
- var pair = encodeURIComponent(name).replace(regexp, "+") + "=" + encodeURIComponent(value).replace(regexp, "+");
- pairs.push(pair);
- }
- return pairs.join("&"); // Concatenate all the name/value pairs, separating them with &.
- }
- };
The POST method uses the AJAX.encodeFormData() function to convert the properties of an object to a string form that can be used as the body of a POST request. This string is then passed to the XMLHttpRequest.send() method and becomes the body of the request. (The string returned by AJAX.encodeFormData() can also be appended to a GET URL; just use a quest-mark character to separate the URL from the data.)
Retrieve the Response
- var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
- xmlHttpRequest.onreadystatechange = function() {
- if (xmlHttpRequest.readyState != 4) {
- // Start to progress
- } else { // The server's response is complete.
- if (xmlHttpRequest.status == 0 || xmlHttpRequest.status == 200) {
- callback(xmlHttpRequest.responseText);
- } else {
- // Error
- }
- }
- }
- xmlHttpRequest.open("POST", "query.php", false);
- xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xmlHttpRequest.send("username=vivian");
Notes on readyState 3
Data is being received from the server.readyState 3 differs somewhat in Firefox and Internet Explorer. Firefox invokes the onreadystatechange
handler multiple times in readyState 3, to provide download progress feedback. A script might use these multiple invocations to display a progress indicator to the user. Internet Explorer, on the other hand, interprets the event handler name strictly, and invokes it only when the readyState value actualy changes. This means that it is invoked only once for readyState 3, no matter how large downloaded document is.
Time Out a Request
- var timer = null;
- var timeout = 1000;
- var xmlHttpRequest = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
- if (timeout) {
- if (timer) {
- clearTimeout(timer);
- }
- timer = setTimeout(function(){
- xmlHttpRequest.abort();
- }, timeout);
- }
- xmlHttpRequest.onreadystatechange = function() {
- if (xmlHttpRequest.readyState != 4) {
- // Start to progress
- } else { // The server's response is complete.
- if (timer) {
- clearTimeout(timer);
- }
- if (xmlHttpRequest.status == 0 || xmlHttpRequest.status == 200) {
- callback(xmlHttpRequest.responseText);
- } else {
- // Error
- }
- }
- }
- xmlHttpRequest.open("POST", "query.php", false);
- xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xmlHttpRequest.send("username=vivian");
Prevent Caching for Internet Explorer
By appending the julian day number to the end of the URL(?timestamp=123412341234), we effectively make each call unique and that means Internet Explorer will not cache the Ajax call as it is wont to do.
回應 (Leave a comment)