我做了一个“向下滚动,激活ajaxrequest,加载更多内容”的功能。
但为了让它正常工作,而不是连续多次触发,因为在ajax数据加载到文档之前,用户会滚动更多内容,所以如果有任何ajaxrequest加载,我需要防止触发更多的ajaxrequest。
代码:
$(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())
人们是怎么做这种事情的?
发布于 2011-09-22 10:11:02
由于您可能可以启动许多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");
这只是简单地跟踪请求的状态并维护一个请求的状态集合,您就拥有了它!
*已编辑!
发布于 2011-09-22 09:56:11
我建议使用旗帜。
标志的概念是打开/关闭某些东西。在这种情况下,您可以指定一个全局布尔(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;
}
});
}
});
https://stackoverflow.com/questions/7512836
复制