Article Introduction: Although browsers support XHR, there are some differences. |
Although browsers support XHR, there are some differences.
1 Timeout settingIE8 adds a timeout attribute to the XHR object, indicating how many milliseconds the request terminates after waiting for the response. After giving timeout this one value, if the browser has not received a response within the specified time, the timeout event is triggered and the OnTimeOut event handler is invoked.
var xhr = creatxhr (); Xhr.onreadystatechange = function (event) { try { if (xhr.readystate ==4) { if ((xhr.status >= && xhr.status <300) Xhr.status = = 304) { alert (xhr.responsetext); } else { alert ("Request was unsuccessful:" + xhr.status); } } catch (ex) { //Assuming OnTimeOut event handler processing } };
Xhr.open ("Get", "timeout.php", true); xhr.timeout = 1000; xhr.ontimeout = function () { alert ("Request did not return in a second."); }; xhr.send (null);
2 Loading Events
Firfox was committed to simplifying the asynchronous interaction model when implementing a version of the Xhr object. The Load event is introduced to replace the ReadyStateChange event. The Load event is triggered when the response is received, so there is no need to check the ReadyState property. The final result is: var xhr = creatxhr (); xhr.onload = function (event) { if ((xhr.status >= && xhr.status <300) Xhr.status = = 304) { alert (xhr.responsetext); } else { alert ("Request was unsuccessful:" + xhr.status); } }; Xhr.open ("Get", "altevents.php", true); xhr.send (null);
The load event is triggered whenever the browser receives a response from the server, regardless of its state. This means that you have to check the status attribute to determine if the data is actually available.
3. Progress Events
Another innovation in Mozilla's XHR is the addition of the Progress event, which periodically triggers when the browser accepts new data, and the OnProgress event handler receives an event object whose target attribute is the XHR object. But it contains two additional attributes: position and totalsize. Where position represents the number of bytes that have been accepted, Totlesize represents the expected number of bytes determined according to the Content-length response header. var xhr = creatxhr (); xhr.onload = function (event) { if ((xhr.status >= && xhr.status <300) Xhr.status = = 304) { alert (xhr.responsetext); } else { alert ("Request was unsuccessful:" + xhr.status); } }; xhr.onprogress = function (event) { var.divstatus = document.getElementById ("status"); divstatus.innerhtml = "Received" + event.position + "of" + event.totalsize + "bytes"; };
Xhr.open ("Get", "altevents.php", true); xhr.send (null);