2011-09-22 77 views
0

我做了一個「向下滾動,啓動ajaxrequest,加載更多內容」的功能。javascript - 我可以檢查ajax是否正在加載?

但是爲了正常工作,並且不會多次連續觸發,因爲在ajax數據加載到文檔之前用戶滾動更多,所以如果有任何ajaxrequests加載,我需要防止觸發更多的ajaxrequests。

代碼:

$(document).scroll(function() { 
var scrollBottom = $(document).height() - $(window).scrollTop(); 
if (scrollBottom < 3000) { 
var offset = parseInt($("#offset").html()) + 10; 
document.getElementById('offset').innerHTML = offset; 
$.ajax({ 
    type: "POST", 
    url: "/", 
    data: "offset=" + offset <?=$ajaxextra?>, 
    success: function(data){ 
    $("#mainContent").append(data); 
    }, 
    error: function(e) { 
    alert(e); 
    } 
}); 
} 
}); 

這就是我想我需要,在僞代碼:

if (scrollBottom < 3000 && !ajax.isLoading()) 

人們怎樣這樣的事情?

回答

2

因爲也許你可以啓動多個AJAX請求,我認爲,最好的解決方案之一 - 基本上,一個可靠的解決方案 - 首先創建請求的數組狀態是這樣的:

var ajaxRequestsState = []; 

當您啓動AJAX請求,不應該將元素添加到這個數組像這樣的:

ajaxRequestsState.push({ requestId: "some identifier" }); 

之後,如果需要檢查,如果沒有主動要求,你可以有一個標誌,像這樣:

function isAsyncRequestActive() { 
    return ajaxRequestsState.length > 0; 
} 

最後,當一個請求結束或失敗,你必須這樣做:

function releaseRequest(requestId) { 
    var requestIndex = 0; 
    var found = false; 

    while(!found && requestIndex < ajaxRequestsState.length) 
    { 
     found = ajaxRequestsState[requestIndex].requestId == requestId; 
     requestIndex++; 
    } 

    if(found) { 
     ajaxRequestsState.splice((requestIndex-1), 1); 
    } 
} 

releaseRequest("identifier of request which ended or failed"); 

這只是跟蹤請求的狀態並保持請求狀態的集合,你就可以擁有它!

*已編輯!

1

我會推薦使用一個標誌。

標誌的概念是打開/關閉某些東西。在這種情況下,您可以指定一個全局布爾(true或false)變量(more on Global Variables in JS)。當你啓動一個給定的ajax請求時,你將該變量設置爲true,當ajax完成時,將它變回false。 您需要做的唯一事情是在您請求任何ajax請求時檢查該全局變量。

考慮到你的例子:

// Global variable. It needs to be outside any function, you can make it the first line in your .js file. 
var isAjaxLoading = false; 
$(document).scroll(function() { 
var scrollBottom = $(document).height() - $(window).scrollTop(); 
if (scrollBottom < 3000 && !isAjaxLoading) { 
var offset = parseInt($("#offset").html()) + 10; 
document.getElementById('offset').innerHTML = offset; 
isAjaxLoading = true; 
$.ajax({ 
    type: "POST", 
    url: "/", 
    data: "offset=" + offset <?=$ajaxextra?>, 
    success: function(data){ 
    $("#mainContent").append(data); 
    isAjaxLoading = false; 
    }, 
    error: function(e) { 
    alert(e); 
    isAjaxLoading = false; 
    } 
}); 
} 
}); 
相關問題