首页 > 解决方案 > 在 AJAX 中发送之前放置 onload 的实际原因是什么

问题描述

我是 JS 新手,正在学习 XHR AJAX。真正让我感到困惑的是,为什么我们必须在发送请求之前加载 onload。我认为在我们发送请求后加载 onload 是合乎逻辑的。如果我们还没有发送请求,我们该如何处理检索到的数据。这是示例代码:

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 ( found in xmlhttp.response )
};
xmlhttp.send();

标签: javascript

解决方案


send() 默认是异步的,onload 是一个回调函数,一旦你从请求中得到响应就会执行,而不是之前。


推荐阅读