HTML and CSS Reference
In-Depth Information
block the user interface while the request is being made. To prevent this, the call should be
asynchronous, as shown here:
var XMLHTTPReadyState_COMPLETE = 4;
var xReq = new XMLHttpRequest();
xReq.open("GET", "myXMLData.xml", true);
xReq.timeout = 2000;
xReq.ontimeout = function () {
$("#results").text("Request Timed out");
}
xReq.onreadystatechange = function (e) {
if (xReq.readyState == XMLHTTPReadyState_COMPLETE) {
if (xReq.status = "200") {
$("#results").text(xReq.response);
} else {
$("#results").text(xReq.statusText);
}
}
}
xReq.send(null);
The onreadystate event is assigned a function to run when the state of the
XMLHttpRequest object is changed. When the request is complete, the readyState changes
to complete ( readyState == 4 ). At this point, the HTTP return status can be evaluated for a
success value such as 200, and then the processing of the XML data can occur.
The same code that has been used so far to retrieve XML data can also be used to make a
request for JSON data. The following update to the code shows this:
var XMLHTTPReadyState_COMPLETE = 4;
var xReq = new XMLHttpRequest();
xReq.open("GET", "myJSONData.json", true);
xReq.timeout = 2000;
xReq.ontimeout = function () {
$("#results").text("Request Timed out");
}
xReq.onreadystatechange = function (e) {
if (xReq.readyState == XMLHTTPReadyState_COMPLETE) {
if (xReq.status = "200") {
$("#results").text(xReq.response);
} else {
$("#results").text(xReq.statusText);
}
}
}
xReq.send(null);
The only difference to this code is the name of the URL being passed. In this case, the
endpoint is a data source that returns JSON-formatted data instead of XML. The JSON is
displayed to the screen in the same way that the XML is displayed.
Search WWH ::




Custom Search