我正在使用jquery每x秒進行一次ajax調用。我還想知道的是,如何註冊相同的Ajax函數以在頁面加載時執行?jquery如何在頁面加載時執行ajax
這裏是我的AJAX功能看起來像(每30秒火災)...
$().ready(function() {
// Poll for bulletin bar message
var url = $.url("/pollBulletin.htm");
pollTimer = setInterval(function() {
$.ajax({
url: url,
type: 'GET',
error: function(data) {
// The server may be down for the night or there may be a
// network blip. As such try to poll 10 times
// if still failing kill the poll.
retryCount = retryCount + 1;
if (pollTimer != null && retryCount >= maxRetries) {
clearInterval(pollTimer);
}
},
success: function(bulletinBarMessage) {
// Once we have a successful poll reset the retry count.
retryCount = 0;
var respContent = "";
respContent += bulletinBarMessage.messageLevel + " : ";
respContent += bulletinBarMessage.message;
$("#mt-news").html('<ul><a href="#" target="_self">' + respContent + '</a></ul>');
}
});
// When communication with the server is lost stop the poll.
}, pollInterval);
});
感謝
@Satpal ya它應該是甚至OP所使用的錯誤語法也會工作,因爲準備好的承諾在內部使用jQuery –
當談到在間隔延遲上發出ajax請求時,請不要使用間隔,請考慮使用而是僅在請求完成後才調用新的調用。即使在這裏,30secs應該足以讓以前的請求完成,但是誰知道會發生什麼...... –