使用 Javascript 处理 XMLHttpRequest 对象
Processing XMLHttpRequest object with Javascript
对于你们大多数人来说,这可能是一个简单的解决方法,但我想不通。
我正在创建一个调用 GET 方法的函数,但我在处理响应时遇到问题。这是我的代码:
function getAPI(url) {
var xhttp = new XMLHttpRequest
xhttp.open('GET',url)
xhttp.send()
return xhttp
}
let xhttp = getAPI('http://127.0.0.1:8000/myapi/')
console.log(xhttp)
console.log(xhttp.response)
当我 console.log xhttp 时,我可以看到正确的 API 响应...但是当我记录 xhttp.response 时,它显示为空值。
XMLHttpRequest
(与 JS 中的几乎所有外部数据访问一样)是 异步.
事件循环不会冻结(完全阻止所有JS和UI)直到响应进来。
您需要使用事件处理程序来确定数据何时可用。
xhttp.addEventListener("load", function () {
console.log(this.response)
});
When I console.log the xhttp I can see the right API response
开发人员工具控制台延迟计算对象。它不会检查响应的值,直到您展开对象(在 属性 更新之后)。
请注意 XMLHttpRequest
、the fetch
API is Promise
based so supports the more convenient async
/ await
syntax 的现代替代品。
对于你们大多数人来说,这可能是一个简单的解决方法,但我想不通。 我正在创建一个调用 GET 方法的函数,但我在处理响应时遇到问题。这是我的代码:
function getAPI(url) {
var xhttp = new XMLHttpRequest
xhttp.open('GET',url)
xhttp.send()
return xhttp
}
let xhttp = getAPI('http://127.0.0.1:8000/myapi/')
console.log(xhttp)
console.log(xhttp.response)
当我 console.log xhttp 时,我可以看到正确的 API 响应...但是当我记录 xhttp.response 时,它显示为空值。
XMLHttpRequest
(与 JS 中的几乎所有外部数据访问一样)是 异步.
事件循环不会冻结(完全阻止所有JS和UI)直到响应进来。
您需要使用事件处理程序来确定数据何时可用。
xhttp.addEventListener("load", function () {
console.log(this.response)
});
When I console.log the xhttp I can see the right API response
开发人员工具控制台延迟计算对象。它不会检查响应的值,直到您展开对象(在 属性 更新之后)。
请注意 XMLHttpRequest
、the fetch
API is Promise
based so supports the more convenient async
/ await
syntax 的现代替代品。