< Previous PageNext Page > Hide TOC

Using XMLHttpRequest

Safari, Dashboard, and WebKit-based applications support the JavaScript XMLHttpRequest object. XMLHttpRequest allows you to easily fetch content from another source and use it within your webpage or widget.

Contents:

Introduction to XMLHttpRequest
Defining an XMLHttpRequest Object
XMLHttpRequest Responses
Security Considerations


Introduction to XMLHttpRequest

XMLHttpRequest is a JavaScript object provided by WebKit that fetches data via HTTP for use within your JavaScript code. It’s tuned for retrieving XML data but can be used to perform any HTTP request. XML data is made available in a DOM object that lets you use standard DOM operations, as discussed in “Using the Document Object Model From JavaScript,” to extract data from the request response.

Typically, you define an XMLHttpRequest object’s options and provide an onload or onreadystatechange handler, then send the request. When the request is complete, you working with either the request’s response text or its response XML, as discussed in “XMLHttpRequest Responses.”

Defining an XMLHttpRequest Object

To create a new instance of the XMLHttpRequest object, call the object’s constructor with the new keyword and save the result in a variable, like this:

var myRequest = new XMLHttpRequest();

Note: If you are writing a webpage, you should be aware that most versions of Microsoft Internet Explorer on Windows do not support creating an XMLHttpRequest object in this way. Jibbering.com has cross-browser sample code at http://jibbering.com/2002/4/httprequest.html if you need to support Internet Explorer prior to version 7.

After you have created a new XMLHttpRequest object, call open to initialize the request:

myRequest.open("GET", "http://www.apple.com/");

The open method requires two arguments: the HTTP method and the URI of the data to fetch. It also can take three more arguments: an asynchronous flag, a username, and a password. By default, XMLHttpRequest executes asynchronously.

After you open the request, use setRequestHeader to provide any optional HTTP headers for the request, like this:

myRequest.setRequestHeader("Cache-Control", "no-cache");

Note: This particular header asks web caches between the browser and the server to not serve the request from a cache. Not all caches respect these flags, however, and some browsers do not consistently respect it, either.

This can be problematic if, for example, you send a request in an onChange handler on a form field. If that request can be cached, any request that changes the field back to a previous value won’t ever reach the server, resulting in the UI not matching the actual values stored on the server.

Thus, if it is absolutely essential that a request not be served from a cache, you should err on the side of caution by adding a timestamp or other nonrecurring value to the end of each URL. For example: http://mysite.mydomain.top/file.html?junktimevalue=1187999959.

To handle the different states of a request, set a handler function for the onreadystatechange event:

myRequest.onreadystatechange = myReadyStateChangeHandlerFunction;

If the only state you’re concerned about is the loaded state (state 4), try using the onload event instead:

myRequest.onload = myOnLoadHandlerFunction;

When the request is ready, use the send method to send it:

myRequest.send();

If your request is sending content, like a string or DOM object, pass it in as the argument to the send method.

XMLHttpRequest Responses

Once your send your request, you can abort it using the abort method:

myRequest.abort();

If you provided an onreadystatechange handler, you can query your request to find its current state using the readyState property:

var myRequestState = myRequest.readyState;

A readyState value of 4 means that content has loaded. This is similar to providing an onload handler, which is called when a request’s readyState equals 4.

When a request is finished loading, you can query its HTTP status using the status and statusText properties:

var myRequestStatus = myRequest.status;
var myRequestStatusText = myRequest.statusText;

Also, you can fetch the request’s HTTP response headers using the getResponseHeader method:

var aResponseHeader = myRequest.getResponseHeader("Content-Type");

To obtain a list of all of the response headers for a request, use getAllResponseHeaders:

var allResponseHeaders = myRequest.getAllResponseHeaders();

To obtain the request’s response XML as a DOM object, use the responseXML property:

var myResponseXML = myRequest.responseXML;

This object responds to standard DOM methods, like getElementsByTagName. If the response is not in a valid XML format, use the responseText property to access the raw text response:

var myResponseText = myRequest.responseText;

Security Considerations

Within Safari, the XMLHttpRequest object can only make requests to URIs in the same domain as the webpage. Also, only URIs with HTTP handlers are allowed.



< Previous PageNext Page > Hide TOC


© 2004, 2008 Apple Inc. All Rights Reserved. (Last updated: 2008-10-15)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.