javascript - 延迟代码执行直到下载完成

标签 javascript ajax

我正在编写一个脚本来为我动态更新论坛页面。这不仅方便,而且我认为这是一个很好的练习,可以更好地熟悉 Javascript 和 DOM。

要获取更新的帖子列表,我必须获取最新版本的页面。我正在使用 XmlHttpRequest 执行此操作:

function getNewDOM(url) {
    console.log("getNewDOM()");
    // Get the page
    var request = new XMLHttpRequest();
    request.open("GET", url, false);
    request.send(null);  

    var new_html = request.responseText;
    var new_dom = document.createElement("div");
    // Strip the HTML down to the contents of the <body> tag.
    new_html = new_html.replace(/<!DOCTYPE.*?body\ id.*?>/, "");
    new_html = new_html.replace(/\/body>.*?<\/html>/, "");
    console.log("Strip HTML");
    new_dom.innerHTML = new_html;

    return new_dom;

}

如您所见,请求当前是同步的。出于我相信你们都知道的原因,这很糟糕。使用异步请求无法完成工作,因为其余代码在页面下载完成之前开始执行。

我认为 setTimeout() 是我需要使用的。是这样的吗?

function getNewDOM(url) {
    console.log("getNewDOM()");
    // Get the page
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.send(null);  

    setTimeout(function() {

        var new_html = request.responseText;
        var new_dom = document.createElement("div");
        // Strip the HTML down to the contents of the <body> tag.
        new_html = new_html.replace(/<!DOCTYPE.*?body\ id.*?>/, "");
        new_html = new_html.replace(/\/body>.*?<\/html>/, "");
        console.log("Strip HTML");
        new_dom.innerHTML = new_html;

        return new_dom;

    }, 15000);

}

问题是我不知道如何将该返回值返回到原始 getNewDOM() 函数,以便我可以将它返回到那里。即使我这样做了,它不会只是在 getNewDOM() 中返回一些未定义的值,因为超时中的函数直到 getNewDOM() 之后才会运行> 完成?这仍然会让我陷入现在的境地。

我是 AJAX 的新手。我知道可能有一些简单的方法可以使用 jQuery,但如果可能的话,我想使用 vanilla Javascript 来完成。

最佳答案

I think setTimeout() is what I need to be using

不,因为您永远不知道异步 ajax 请求何时完成。您需要绑定(bind)到 readystatechange 事件:

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (request.readyState==4 && request.status==200) {
        // Inside here is the only safe place to use request.responseText;
    }
}

关于javascript - 延迟代码执行直到下载完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12309127/

相关文章:

javascript - 从 electron 中的 html 中检索一个类

javascript - YouTube视频作为div背景不适用于所有视频

asp.net - 抓取由 asp.net/AJAX (__doPostBack) 管理的 html 分页

jquery - 我在选择之前有一张图片,当我选择它时应该将其更改为另一张图片

javascript - ng-controller 在 DOM 准备就绪后加载,Angular 未接收到

jquery - ajax调用成功后如何使用数据

javascript - svg 将矩阵符号转换为旋转/平移

javascript - 如果 startTime 小于当前时间,在这种情况下如何计算正确的时间?

javascript - 测试 firebase firestore 中未设置的值

php - 使用自定义 MVC 从 JQuery ajax()、PHP 和 MySQL 检索 JSON 数据