Parameter "true" In Xmlhttprequest .open() Method
Solution 1:
I wrote a more detailed article here, but this is the basic idea.
Setting it to true means you are making an asynchronous request. That means the code does not pause until the http request is complete. A synchronous call locks up the browser so nothing else runs. That can cause problems, so people prefer asynchronous.
The XHR object updates us on what it is doing. It gives us the updates with the onreadystatechange event. We register a function with it so we can keep track of its status. The onreadystatechange gets called 4 times. Each with a different state
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
The data is available to us when the readystate is 4.
Now in the code you posted, it is checking for the complete state and it makes sure that the status is 200 [ok]
if(xml_req.readyState == 4 && xml_req.status == 200){
The value for xmlResponse will be undefined if you try to use it somewhere else in the code before it is returned. An example
ml_req.send(null);
alert(xmlResponse );
One of the very first articles on the XMLHttpRequest article might be a good read for you. Apple Article on xmlhttpreq
Solution 2:
The important thing to understand is that your onreadystatechange
handler is not executed immediately. And it is executed more than once. It may be easier to conceptualize, if you break the pieces out into individual functions:
functionmakeRequest(url)
{
var xhr = newXMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = receiveResponse;
xhr.send();
}
functionreceiveResponse(e)
{
if (this.readyState == 4)
{
// xhr.readyState == 4, so we've received the complete server responseif (this.status == 200)
{
// xhr.status == 200, so the response is goodvar response = this.responseXML;
...
}
}
}
First, makeRequest
is called and then exits. Then, as soon as we hear anything back from the server, receiveResponse
is called. Each time, we check to see if the response is fully received, and only then do we continue to process that response.
Post a Comment for "Parameter "true" In Xmlhttprequest .open() Method"