2012-09-06 68 views
1

我正在编写一个脚本,可以为我动态更新论坛页面。这不仅方便,但我认为这是一个很好的练习,以更熟悉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来做到这一点,如果可能的话。

回答

1

我认为setTimeout()还是什么,我需要使用

没有,因为你永远不知道什么时候异步Ajax请求将完成。你需要的是绑定到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; 
    } 
} 
1

与其等待15秒你应该使用readystatechange事件

request.onreadystatechange = function() { 
    if (request.readyState === 4 && request.status === 200) { 
     // code which should be executed once the download has finished 
     // ... 
    } 
} 
+0

那是另一件事我试过了。但是,我仍然无法将返回值返回到getNewDOM()那样,我可以吗?它不会仍然以一个未定义的值结束函数,因为函数将在状态改变之前结束? – user1653251

+0

任何需要Ajax调用响应的代码都必须移动到'readystatechange'处理程序中,或者至少必须在那里调用代码,以便将响应传递给它 – Andreas

+0

所以,你说我需要将调用getNewDOM()的函数分解为多个部分,以便后一部分从getNewDOM()(或者onreadystatechange处理程序)调用? – user1653251

相关问题