Aborting an HTTP Request


XMLHttp.abort(); 

Depending on the browser, only a limited number of HTTP requests can be done at a time. Especially if you have a page with multiple AJAX components (the modern term for this is "mashup"), you may run into trouble. Therefore, aborting an HTTP request may become a necessity.

The method used for that is abort(). The following code aborts the request if it has not been fully executed after five seconds. To demonstrate this behavior, the PHP script delay.php that is called by the code takes 10 seconds to execute. Also note that the readyState property is checked first: if it is 0 or 4, there is nothing to abort.

Aborting an HTTP Request (xmlhttpabort.html)

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/xmlhttp.js"></script> <script language="JavaScript"   type="text/javascript"> var XMLHttp = getXMLHttp(); XMLHttp.open("GET", "delay.php?" + Math.random()); XMLHttp.onreadystatechange = handlerFunction; XMLHttp.send(null); window.setTimeout("timeout();", 5000); function handlerFunction() {   if (XMLHttp.readyState == 4) {     window.alert("Returned data: " +                  XMLHttp.responseText);   } } function timeout() {   if (XMLHttp.readyState != 4 &&       XMLHttp.readyState != 0) {     XMLHttp.onreadystatechange = function() { };     XMLHttp.abort();     window.alert("Request aborted");   } } </script> 

Five seconds after loading this page, the request is aborted.

Tip

Appending the result of Math.random() to the URL to call causes caching for the script delay.php to be disabled, since the URL is a different one every time.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net