为什么在XMLHttpRequest中编写send()之前为什么要编写onload()函数 [英] Why do we write onload() function before we write send() in XMLHttpRequest
问题描述
我是XMLHttpRequest的新手.我不明白为什么我们要在send()函数之前编写onload()函数.onload()函数处理收到的响应,send()函数将请求发送到服务器.因此,根据我的理解,onload()必须在send()函数之后编写.有人可以帮助您了解这一点.
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();
推荐答案
我不明白为什么我们要在
send()
函数之前编写onload()
函数.
因此,在发送请求之前 便已安装了加载处理程序,因为发送请求将导致调用处理程序(如果成功).
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()
函数处理收到的响应,然后send()
函数向服务器发送请求.因此,根据我的理解,必须在send()
函数之后编写onload()
.
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.
(通过XHR基础架构)(或可能在此期间)调用 send
后被调用.将其分配给 onload
时,并不是调用.您只是在定义它,以便XHR需要调用它时就可以使用它.
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.
发生的事情是这样:
- 您创建XHR.
- 您为其
load
事件注册一个处理程序(在您的情况下,是将一个函数分配给onload
). - 您拨打
发送
.
- You create the XHR.
- You register a handler for its
load
event (in your case, by assigning a function toonload
). - You call
send
.
- 浏览器启动(并可能完成)请求
load
事件.这会查找当前为 load
注册的所有处理程序,并将对这些处理程序的调用排队(如果有的话).只要有主要的JavaScript线程可以运行这些调用,就可以运行它们.
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.通常,您会以错误的方式进行处理,因为到请求完成时,您会在其中放置 load
处理程序;但不是 总是 . load
是一个事件.如果可以立即(例如,从缓存中)满足请求,则浏览器可以在 send
期间触发 load
,并查看是否存在在对 send
的调用期间,任何 load
处理程序,如果没有,则不将对任何回调的调用排队.稍后,当您附加处理程序时,该事件已被触发(当未附加任何事件时).
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).
因此,您必须在调用 send
之前附加处理程序.
So you have to attach the handler before calling send
.
这篇关于为什么在XMLHttpRequest中编写send()之前为什么要编写onload()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!