2015-10-20 74 views
0

我有一個網頁,我從服務器獲取一些數據。我用servlet從服務器獲取數據。我需要每隔5秒鐘獲取一次數據inerval.I在我的腳本中使用了ajax調用,但是在幾次調用之後,網頁變得沒有響應。我發現了一件事,我在這裏再次替換了整個html頁面,我怎樣才能從輸出html內容(這裏是page_html)中分離出特定的div。我只想ajax調用後網頁變得沒有響應

setInterval("update_content();", 5000); 

function update_content(){ 
    $.ajax({ 
     url: "url", // post it back to itself - use relative path or consistent www. or non-www. to avoid cross domain security issues 
     type: "POST", 
     async: true, 
     cache: false, // be sure not to cache results 
    }) 
    .done(function(page_html) { 
     var newDoc = document.open("text/html", "replace"); 
     newDoc.write(page_html); 
     newDoc.close();   
    });  
}  
+1

使用'setInterval(update_content,5000);'而不是'setInterval(「update_content();」,5000);'。 –

+0

在控制檯中是否有任何錯誤? –

+0

這很奇怪。你能在JSFIddle上發佈最小可重現的例子嗎? –

回答

0

我怎麼能單獨一個特定的div從輸出HTML內容替換DIV(這裏page_html)。我想替換DIV只有

您可以使用jQuery html()方法只是改變div的內容。

<div id="yourDivId"> 
</div> 

JS:

function update_content(){ 
    $.ajax({ 
     url: "url", // post it back to itself - use relative path or consistent www. or non-www. to avoid cross domain security issues 
     type: "POST", 
     async: true, 
     cache: false, // be sure not to cache results 
    }) 
    .done(function(page_html) { 
     $("#yourDivId").html(page_html); 
    });  
}  

此方法將加載使用AJAX的HTML,然後用加載的數據替換的HTML #yourDivId內容。這是AJAX通常用於的。

+0

我有一個響應html,並根據這個如果我有一個div,我正在做一個ajax調用,它會將響應數據加載到我的div上嗎? –

+0

我想加載一個特定的div來響應我的div id,這裏的整個響應都會加載到我的div id上嗎? –

+0

@JamesHoffman是的,整個迴應將取代目標HTML。爲了使它成爲AJAX風格,你只需要返回'div'內容作爲迴應,而不是整個頁面。 –