Sending a Synchronous Request


XMLHttp.open("GET", "phrasebook.txt", false); 

By default, HTTP requests via XMLHttpRequest are asynchronous, which explains the need for a callback function. However, when you set the third parameter of the open() method to false, the request is a synchronous one, which means that the script execution is stopped until data comes back from the server. The following code makes use of that:

Sending a Synchronous Request (xmlhttpsync.html)

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/xmlhttp.js"></script> <script language="JavaScript"   type="text/javascript"> window.onload = function() {   var XMLHttp = getXMLHttp();   XMLHttp.open("GET", "phrasebook.txt", false);   XMLHttp.send(null);   document.getElementById("output").innerHTML =     "Returned data: " + XMLHttp.responseText; } </script> <p >Calling the server ...</p> 

Note that the whole code is executed only after the full page has been loaded; otherwise, the access to the output HTML element may fail.

Warning

Synchronous calls may be convenient, but from a usability and performance point of view, they should be avoided. The script execution stops completely while the call is made, which could turn into a real nightmare with slow connections or servers under a heavy load.





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