Java Reference
In-Depth Information
localStorage.setItem("lastAdNumber", nextNumber);
document.write(ads[nextNumber]);
Chapter 14
exercise 1 Question
Extend the
HttpRequest
module to include synchronous requests in addition to the asynchronous
requests the module already makes. You'll have to make some adjustments to your code to
incorporate this functionality. (Hint: Create an
async
property for the module.)
exercise 1 Solution
function HttpRequest(url, callback) {
this.url = url;
this.callBack = callback;
this.async = true;
this.request = new XMLHttpRequest();
};
HttpRequest.prototype.send = function() {
this.request.open("GET", this.url, this.async);
if (this.async) {
var tempRequest = this.request;
var callback = this.callBack;
function requestReadystatechange() {
if (tempRequest.readyState == 4) {
if (tempRequest.status == 200) {
callback(tempRequest.responseText);
} else {
alert("An error occurred while attempting to " +
"contact the server.");
}
}
}
this.request.onreadystatechange = requestReadystatechange;
}
this.request.send(null);
if (!this.async) {
this.callBack(this.request.responseText);
}
};
It's possible to add synchronous communication to your
HttpRequest
module in a variety of ways.
The approach in this solution refactors the code to accommodate a new property called
async
,