106 Part I: Core Ideas
var percentComplete = (e.position / e.totalSize)*100;
document.getElementById("responseOutput").style.display = "";
document.getElementById("responseOutput").innerHTML += "<h3>reponseText -
" + Math.round(percentComplete) + "%</h3>" + e.target.responseText;
}
This Firefox-specific example can be run at http://ajaxref.com/ch3/partialprogress.
html and should be quite encouraging because it suggests that there will be a time in the
near future when we will be able to very quickly get an accurate sense of request progress
beyond a spinning circle animated GIF.
NNOT EOTE A limitation of using XML responses is that you cannot look at partial responses. The reason
for this is that an entire XML packet is required for parsing the tree properly.
Partial Responses with readyState
It is possible to perform the same partial data example using a timer to wake up every so
often and look at responseText. In this case, the callbacks are set to wake up every 50 ms
using either setTimeout() or setInterval(). The callbacks then handle the partial data.
var url = "http://ajaxref.com/ch3/largefile.php";
var xhr = createXHR();
if (xhr)
{
xhr.open("GET", url, true);
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(null);
window.setTimeout( function() {handlePartialResponse(xhr);}, 50);
}
In handlePartialResponse we look at the responseText field to grab whatever data
has been provided. We can also look at the Content-Length response header, assuming it
is provided to calculate the percentage progress.
function handlePartialResponse(xhr)
{
if (xhr.readyState == 3)
{
document.getElementById("responseOutput").style.display = "";
var length = xhr.getResponseHeader("Content-Length");
var percentComplete = (xhr.responseText.length / length)*100;
document.getElementById("responseOutput").innerHTML += "<h3>reponseText -
" + Math.round(percentComplete) + "%</h3>" + xhr.responseText;
}
/* wake up again in 50ms to handle more data if not done now */
if (xhr.readyState != 4)
window.setTimeout( function() {handlePartialResponse(xhr);}, 50);
}