微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在异步函数中更新 HTML

如何解决在异步函数中更新 HTML

我正在尝试更新 GET 函数内的 Html。当我在 request.onload 之后立即打印时,内容会更新,但是,在函数之外它保持不变:

function locationData(zip_code)
{
  var request = new XMLHttpRequest(); 
  
  request.open("GET",url,true);
  request.send();
  request.onload = () =>
  
  {
     if (request.status == 200) 
     {
        data = JSON.parse(request.response);
        document.getElementById("forecast").innerHTML = "Upadted content";
        console.log(document.getElementById("forecast").innerText); // **Updated content**
        
     }
     else {(console.log("error"));} 
  }
  console.log(document.getElementById("forecast").innerText); //**Old content**
} 
console.log(document.getElementById("forecast").innerText); //**Old content**


window.onload = function() {
    console.log(document.getElementById("forecast")); 
    
    }

我怀疑异步功能在请求更新内容时没有按时停止。这就是为什么我正在尝试 window.onload,但仍然无法正常工作。

感谢任何帮助。

解决方法

这一切都符合预期,也许你可以这样想象:

locationData() {
  // now (== when locationData is called)
  // now
  // now
  request.onload = () => {
    // future
    // future
    // future
  }
  // now
  // now 
  // now
}

您只需放弃使用仅在未来可用的数据即可。如果你以后想对数据做点什么,那么你也必须把那个逻辑放在未来。

并且您已经在将来更新 (....innerHTML = something),因此您的代码可能按预期工作,当然除了 console.logs。

请注意,如果您在浏览器控制台中记录一个对象,您将看到它的当前状态,而不是“何时”记录它。这是一个陷阱,但当你知道它是如何工作的时候很方便。您可以 console.log(JSON.parse(JSON.stringify(obj))) 以确保您看到的对象与记录时一样。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。