我是 XMLHttpRequest 的新手。我不明白为什么我们要在 send() 函数之前编写 onload() 函数。 onload() 函数处理我们收到的响应,send() 函数向服务器发送请求。所以根据我的理解,onload()必须写在send()函数之后。有人可以帮助理解这一点吗?
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();
我不明白为什么我们要在
函数之前写onload()
函数。send()
以便加载处理程序在发送请求之前就位,因为发送请求将导致调用处理程序(如果成功)。
在(由 XHR 基础设施)调用
onload()
函数处理我们收到的响应,send()
函数向服务器发送请求。所以根据我的理解,onload()
必须写在send()
函数之后。
send
之后(或可能在调用期间),它被 称为
。当您将其分配给
onload
时,您并不是在“调用”它。您只需定义它,以便当 XHR 需要调用它时它就在那里。发生的事情是这样的:
您创建 XHR。
load
onload
分配一个函数)。
您致电
send
浏览器开始(并可能完成)请求
load
load
处理程序,并对这些处理程序的调用进行排队(如果有)。一旦主 JavaScript 线程可用于运行这些调用,它们就会立即运行。
很多时候,您可能会以错误的方式进行操作,因为当请求完成时,您已经将
load
总是。
load
是一个事件。如果可以立即满足请求(例如,从缓存),则浏览器可以在
load
期间触发send
,并查看是否有任何
load
处理程序during
对
send
的调用,如果没有,则不对任何回调的调用进行排队。稍后,当您附加处理程序时,该事件已被触发(当没有附加处理程序时)。
因此,您必须在调用
send
之前附加处理程序。xhr.onload 是一个设置为函数的事件处理程序。当 HTTP 请求成功完成时将调用此函数。 onload 事件通常在收到整个 HTTP 响应时触发。 所以,你的理解是100%正确的。如果你在调用 xhr.send() 之后编写 xhr.onload 它将完美工作。在 xhr.send 之后或之前,无论您在何处编写 xhr.onload,它都会在收到响应后执行。
document.getElementById('get-button').addEventListener('click',()=>{
const xhr = new XMLHttpRequest();
xhr.open('GET','https://jsonplaceholder.typicode.com/todos/1');
xhr.responseType = 'json';
xhr.send();
xhr.onload = function(){
console.log(xhr.response);
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Get data from server</h1>
<button id="get-button">Get Data</button>
<script src="style.js"></script>
</body>
</html>