AJAX - The Complete Reference

(avery) #1

Chapter 3: XMLHttpRequest Object 105


PART I


With Firefox, it is possible to set the multipart property of an XHR instance to true to
enable support for this format. Since this is a proprietary feature, you will likely use the
onload event handler, which fires when data is loaded (readyState = 4), but you should
also be able to set onreadystate change approach for your callback as well, if you like.

var url = "http://ajaxref.com/ch3/multipart.php";
var xhr = createXHR();
if (xhr)
{
xhr.multipart = true;
xhr.open("GET", url, true);
xhr.onload = handleLoad;
xhr.send(null);
}

When the data is received, just look at it as a normal XHR, though given the format, you
will likely be only using responseText.

function handleLoad(event)
{
document.getElementById("responseOutput").style.display = "";
document.getElementById("responseOutput").innerHTML +=
"<h3>xhr.responseText</h3>" + event.target.responseText;
}

To see this example working under supporting browsers, visit http://ajaxref.com/ch3/
multipart.html.

onProgress and Partial Responses


Firefox already implements a few useful event handlers for the XMLHttpRequest object. The
most interesting is the onprogress handler, which is similar to readyState with a value of
3 but is different in that it is called every so often and provides useful information on the
progress of any transmission. This can be consulted to not only look at the responseText as
it is received, but also to get a sense of the current amount of content downloaded versus the
total size. The following code snippet sets up an XHR to make a call to get a large file and
associates a callback for the onprogress handler:

var url = "http://ajaxref.com/ch3/largefile.php";
var xhr = createXHR();
if (xhr)
{
xhr.onprogress = handleProgress;
xhr.open("GET", url, true);
xhr.onload = handleLoad;

xhr.send(null);
}

The handleProgress function receives an event object that can be examined to
determine the progress made versus the total size, as well as to access the received content
in responseText.

function handleProgress(e)
{
Free download pdf