javascript - 在 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();
解决方案
send() 默认是异步的,onload 是一个回调函数,一旦你从请求中得到响应就会执行,而不是之前。
推荐阅读
- c++ - read() 没有按预期阻塞
- sql - 如何处理 PostgreSQL 中的大小写敏感问题
- mysql - 如何在 SQL 中查询单个单元格中的多个值
- arrays - 为什么Gson允许普通数组声明,然后在Map中访问它时抛出ClassCastException?
- amazon-web-services - 具有两个 IAM 角色的两个 AWS Lambda 函数
- php - 通过受保护的 SendinBlue 对象循环
- c# - ASP.NET Core 3.1 IOptions - 无法从 Helper 类中的文件初始化配置
- react-native - 如何在 expo 应用程序中使用 jest 模拟 SQLite.openDatabase?
- reactjs - 如何测试元素是否存在?
- php - 使用 wp-login 根据 WooCommerce 会员级别重定向登录