Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

372 CHAPTER 8 Websites and services


if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsonObject = JSON.parse(xmlhttp.response);
result.innerHTML = jsonObject.result;
}
}
xmlhttp.addEventListener(“progress”, updateProgress, false);
xmlhttp.open("GET", "/addition?x=" + x + "&y=" + y , true);
xmlhttp.send();
}

function updateProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//display percenComplete
} else {
// Need total size to compute progress
}
}
The server must provide a value for both the loaded property and the total property for
this to work properly. The progress event might be most useful when loading a large amount
of data to the browser or loading a large file.

Handling errors
If an error occurs, the HTTP status code will be something other than 200. You can also sub-
scribe to the error and abort events, as shown in the following code example.
function addNumbers() {
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
var result = document.getElementById('result');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsonObject = JSON.parse(xmlhttp.response);
result.innerHTML = jsonObject.result;
}
}
xmlhttp.addEventListener("progress", updateProgress, false);
xmlhttp.addEventListener(“error”, failed, false);
xmlhttp.addEventListener(“abort”, canceled, false);

xmlhttp.open("GET", "/addition?x=" + x + "&y=" + y , true);
xmlhttp.send();
}

function transferFailed(evt) {
alert(“An error occurred”);
}

function canceled(evt) {
alert(“canceled by the user”);
}
Free download pdf