[英]Ajax call on setInterval timer not working
我有一個非常簡單的小過程。 我有一個間隔計時器,當它到期時,它將對服務器進行ajax調用。 使用返回的json,它解析出並更新DOM。 setInterval設置為一秒。 然后,服務器對數據庫執行非常簡單的SELECT。 如果執行查詢,它將執行一個毫秒的查詢。
在我們的測試服務器上,它工作正常。 但是,當將其部署到我們的客戶時,大多數情況下實際上並沒有訪問數據庫。 我們可以在查詢分析器中看到它。 查詢應該是連續不斷的,但是充其量是零散的,每次命中之間通常間隔40秒或更長時間。
這是代碼:
setTimeout(function run() {
// When the timer elapses, get the data from the server
GetData(0);
setTimeout(run, _refreshRate);
}, 1000);
function GetData(isFirstLoad) {
//console.log("Attempting to obtain the data...");
jQuery.ajax({
url: "something.ashx",
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
//console.log("Got the data.");
ParseJson(resultData);
// show the last refresh date and time
$('#refreshTime').html(GetDateTime());
},
error : function(xhr, textStatus, errorThrown) {
if (textStatus == 'timeout') {
//console.log("Timeout occured while getting data from the server. Trying again.");
// If a timeout happens, DON'T STOP. Just keep going forever.
$.ajax(this);
return;
}
},
timeout: 0,
});
}
ParseJson(resultData);
工作正常。 有了這條線...
$('#refreshTime').html(GetDateTime());
...時間每秒鍾刷新一次,就像發條一樣,即使數據庫永遠不會受到影響。
而且我可以在error
內部的調試工具中放置一個斷點,而這個斷點永遠不會被擊中。
如果我們單擊刷新,它會起作用或等待幾秒鍾(我們可以看到查詢命中了數據庫),但隨后又變慢了。
令人沮喪的是,它可以在我們的測試服務器上完美運行。 但是顯然有一些我忽略的事情。
編輯:
好的,這真的很奇怪。 當我打開調試器時,它可以工作。 關閉調試器后,它將立即停止工作。 我什至不必讓網絡標簽運行並捕獲事件。 只需打開調試器窗口即可使其工作。
這就是IE,客戶端正在使用它,因此這是我們唯一的選擇。
在這里找到答案:
事實證明,只有IE瀏覽器會緩存ajax響應。 您必須告訴它不要。 添加cache: false
就成功了。
function GetData(isFirstLoad) {
//console.log("Attempting to obtain the data...");
jQuery.ajax({
url: "something.ashx",
type: "GET",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function(resultData) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.