2012-07-20 31 views
4
var refreshId_hxlatestposts = setInterval(function() { 
var el = $("#hxlatestposts"); 
var req = $.get("example.php"); 
el.fadeOut('slow', function() { 
    req.done(function(data){ 
     el.html(data).fadeIn('slow'); 
    }); 
}); 
}, 60000); 

這就是我用來刷新div的每一分鐘,有時它會掛起,當它從網站獲取飼料是down或什麼的。我想要一些如何有超時,所以如果它不能在X秒內加載PHP文件,然後返回'加載失敗'。添加一個超時加載()

回答

2

jQuery文檔(.ajaxSetup())建議使用.ajaxSetup()將值f或timeout,而不是在個別請求中使用它。

如果請求失敗,您可以使用request.fail()註冊一個函數。

$.ajaxSetup({ 
    timeout: 5000 
}); 

var refreshId_hxlatestposts = setInterval(function() { 
    var el = $("#hxlatestposts"); 
    var req = $.get("example.php"); 
    el.fadeOut('slow', function() { 
     req.done(function(data) { 
      el.html(data).fadeIn('slow'); 
     }); 
     req.fail(function(jqXHR, textStatus) { 
      el.html('Fail to load').fadeIn('slow'); 
     }); 
    }); 
}, 60000); 
+0

如果我是使用此代碼剪斷的X,我會只需要在JS文件的頂部放置一次ajaxSetup?沒關係,我想我應該閱讀文檔。 使用任何函數的所有後續Ajax調用將使用新的設置,除非被單個調用覆蓋,直到下一次調用$ .ajaxSetup()。 – Keelan 2012-07-20 20:33:35

2

不錯的使用延緩對象。

如果用$.ajax代替$.get,則可以添加超時。

var req = $.ajax({ 
    url: "example.php", 
    type: "GET", 
    timeout: 5000 // 5 seconds 
}); 

,然後添加故障處理程序

req.done(function(){...}).fail(function(){ 
    alert("failed to load"); 
}); 
1

你要檢查傳入響應的狀態,以確保服務返回的200個OK狀態。這比僅僅等待超時更可靠 - 你會知道它是否是好數據,或者可以通過將超時放入完整函數來決定重試。

$.ajax({ 
    //...   
    success: function(data, textStatus, xhr) { 
     console.log(xhr.status); 
     //handle status codes etc. 
     // then set your timeout 

    }, 
    complete: function(xhr, textStatus) { 
     console.log(xhr.status); 
     //handle status codes etc. 
     // then set your timeout 

    }, 

    // OR 

    fail: function(xhr, textStatus){ 
     //retry code or timeout 
    } 

    }); 
1

jQuery的$不用彷徨,不過是爲了$就簡寫,這是當需要更大的靈活性,使用(你的情況,是)

替換$.get("example.php");有: $.ajax({ type: "GET", url: "example.php", timeout: X*1000, }).done(function(data) { el.fadeOut('slow', function() { el.html(data).fadeIn('slow'); }); }, 60000); });

哪裏X是您希望它等待的秒數(超時)

+0

Sry基因,我做了一些修改爲新密碼,這樣你就可以取代下面的'變種EL = $(「#hxlatestposts」)的代碼;' – 2012-07-20 18:30:11