2015-08-25 141 views
0

我有一個儀表板,其中包含儀表板內容的div。這是每10秒從本地數據庫刷新自己。 (還有另一個時鐘功能)。這是我的代碼:jQuery自動刷新 - 單擊按鈕時中止頁面加載

setTimeout('sensorcells_load()', 10000); 
function sensorcells_load() 
{ 
    jQuery('#sensorcells').load('dashboard_content.php'); 
    setTimeout('sensorcells_load()', 10000); 
    clock();   
} 

我的問題是,當我點擊在儀表板上的按鈕時,有時需要一定的時間來獲得詳細信息頁面。我想這是因爲我需要等待.load('dashboard_content.php')。點擊任何詳情按鈕時,如何停止頁面加載?

回答

1

嘗試使用window.onbeforeunload與全球.ajax()功能和.abort()

var loadTimeout = setTimeout('sensorcellsLoad()', 3000); 
function sensorcellsLoad(){ 
    window.ajaxRequest = jQuery.ajax({ 
     url: 'dashboard_content.php', 
     success: function(data) { 
     jQuery('#sensorcells').html(data); 
     loadTimeout = setTimeout('sensorcellsLoad()', 3000); 
     } 
    }); 
    clock(); 
} 


window.onbeforeunload = function() { 
    clearTimeout(loadTimeout); 
    window.ajaxRequest.abort(); 
}; 

無論您如何卸載它,它在卸載當前頁面之前總是會停止超時。

而且,加入類似下面的全球varible會是個不錯的做法:

var pageIsBeingRefreshed = false; 

window.onbeforeunload = function() { 
    pageIsBeingRefreshed = true; 
}; 

這將使得它可以過濾如果發生因爲實際的錯誤或整個頁面重新加載的Ajax錯誤。

if (pageIsBeingRefreshed) { 
    return; 
} else { 
    //Do some actual error handling. 
} 

更新: 我已經修改了原來的代碼,以利用全球的窗口對象爲Ajax處理。

的jsfiddle可以在這裏找到:http://jsfiddle.net/cnoL26ve/1/

+0

謝謝Magnus。如果我們停止setTimeout,它是否會停止已經啓動的頁面加載?因爲我的問題是,將數據從數據庫加載到儀表板需要時間(需要3-5秒)。我需要停止從數據庫加載。 – cvdogan

+0

'clearTimeout'不會停止正在執行的ajax調用。 但是使用'.abort()'會。 我會用這段代碼更新我的帖子。 –

+0

如何在我的代碼中使用.abort()? – cvdogan

0

使用clearTimeout()一樣,

var t=setTimeout('sensorcells_load()', 10000); 
function sensorcells_load() 
{ 
    jQuery('#sensorcells').load('dashboard_content.php'); 
    t = setTimeout('sensorcells_load()', 10000); 
    clock();   
} 
// let your button id is stopLoading 
$('#stopLoading').on('click',function(){ 
    clearTimeout(t); 
}); 

更新:如果你想的時候我們後您的數據庫操作進行再使用load()回調一樣,

setTimeout('sensorcells_load()', 10000); 
function sensorcells_load() 
{ 
    jQuery('#sensorcells').load('dashboard_content.php',function(){ 
     setTimeout('sensorcells_load()', 10000); // wait for response then again load after 10 seconds 
    });   
    clock();   
} 
+0

我問了同樣的問題馬格努斯。如果我們停止setTimeout,它是否會停止已經啓動的頁面加載?因爲我的問題是,將數據從數據庫加載到儀表板需要時間(需要3-5秒)。我需要停止從數據庫加載。 – cvdogan

+0

用load()回調試試我的更新答案。 –

相關問題