I am new to XMLHttpRequest. I dont understand why do we write onload() function before send() function. onload() function process the response what we receive and send() function sends a request to server. So onload() has to be written after send() function as per my understanding. Can somebody help to understand this.
var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';
xmlhttp.open(method, url, true);
xmlhttp.onload = function () {
// Do something with the retrieved data
};
xmlhttp.send();
I dont understand why do we write
onload()
function beforesend()
function.
So that the load handler is in place before the request is sent, since sending the request will result in calling the handler (if successful).
onload()
function process the response what we receive andsend()
function sends a request to server. Soonload()
has to be written aftersend()
function as per my understanding.
It's called after send
is called (by the XHR infrastructure) (or potentially during). When you assign it to onload
, you're not calling it. You're just defining it so that it's there when XHR needs to call it.
Here's what happens:
load
event (in your case, by assigning a function to onload
).send
.
load
event. That looks for any currently-registered handlers for load
and queues calls to those handlers, if any. Those calls are run as soon as the main JavaScript thread is available to run them.Very often, you'd get away with doing it the wrong way around because by the time the request completes, you'll have put the load
handler there; but not always. load
is an event. If the request can be satisfied immediately (for instance, from cache), the browser could fire load
during send
, and look to see if there's any load
handler during the call to send
, and if there isn't, not queue a call to any callback. Later when you attach a handler, the event has already been fired (when none were attached).
So you have to attach the handler before calling send
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With