Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

javascript - Why do we write onload() function before we write send() in XMLHttpRequest

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I dont understand why do we write onload() function before send() 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 and send() function sends a request to server. So onload() has to be written after send() 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:

  1. You create the XHR.
  2. You register a handler for its load event (in your case, by assigning a function to onload).
  3. You call send.
    1. The browser starts (and potentially finishes) the request
  4. When the request finishes, if it's successful, the browser's XHR handling triggers the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...