2012-09-06 75 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

相關問題