Javascript 为什么我的Ajax调用没有通过readystate 1?
我觉得我做的一切都是对的,但是我的Ajax调用没有得到响应,我错过了什么Javascript 为什么我的Ajax调用没有通过readystate 1?,javascript,ajax,Javascript,Ajax,我觉得我做的一切都是对的,但是我的Ajax调用没有得到响应,我错过了什么 function loadMedia() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon', true); console.log(xhr.readyState); xhr.onload = function() { if(xhr.status === 200 ) {
function loadMedia() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon', true);
console.log(xhr.readyState);
xhr.onload = function() {
if(xhr.status === 200 ) {
console.log(true)
let txt = JSON.parse(xhr.responseText);
console.log(txt)
for(let i in txt) {
console.log(txt[i])
}
}
}
console.log(xhr.readyState)
xhr.send()
}
它只停留在readystate 1上。
xhr。readystate
不会帮助您编写代码,您必须调试是否调用了onload
console.log(xhr.readyState); // sync
xhr.onload = function() {
// async inside the function call, when onload
};
console.log(xhr.readyState) // sync, this isn't waiting AJAX response
如果将console.log(xhr.readyState)
放入回调fn中,它将记录其他值,但请记住还要处理onerror
我建议您使用addEventListener
listenersapi,而不是老式的事件处理程序
希望有帮助 异步与同步。您正在创建并启动XHR,然后在XHR有机会执行任何操作之前记录两次就绪状态。看这回答了你的问题吗?顺便说一句,这是一种相当古老的做事方式。Fetch API现在是一种方式。我建议使用
onreadystatechange
作为监听事件。它专门监视属性值的变化。是的,但这里的问题是为什么要观察状态变化?好像他在看一篇老文章。。。addEventListener(“加载”)是您所需要的