出于某种奇怪的原因,下面的ajax函数会触发两次。 loadMoreResults(); function用于从服务器检索数据。 我使用谷歌开发者工具跟踪发送到服务器的数据,它显示ajax请求连续两次被触发。 我想这会在用户快速滚动时发生。
//Executed when user has scrolled bottom of the page $(window).scroll(function (e) { if ($(window).scrollTop() == $(document).height() - $(window).height()) { loadMoreResults(); } });有关如何防止这种情况发生的任何想法? 感谢你的帮助。
For some weird reason the ajax function below is firing twice. The loadMoreResults(); function is used to retrieve data from server. I tracked the data sent to the server using google developer tool it showed that the ajax request was fired twice in a row. I guess this happens when the user scroll fast.
//Executed when user has scrolled bottom of the page $(window).scroll(function (e) { if ($(window).scrollTop() == $(document).height() - $(window).height()) { loadMoreResults(); } });Any idea on how to prevent this from happening? Appreciate your help.
最满意答案
正如您所说,可能是因为用户滚动太快而且文档无法使用新结果进行更新。
尝试使用一个标志,该标志将阻止在函数仍在执行时调用loadMoreResults() 。
在函数启动时将其设置为true,最后,在获得结果后,将其设置为false。 在将标志设置为true之前,可以将标志的检查放在loadMoreresults()函数的开头。
例如:
function loadMoreResults() { if (flag) return; flag = true; [...] flag = false; }As you said, it could be because the user is scrolling too fast and the document does not get to be updated with the new results.
Try using a flag that will prevent calling the loadMoreResults() while the function is still executing.
You set it to true when the function starts and at the end, after you get your results, you set it to false. The check of the flag can be placed right at the beginning of the loadMoreresults() function, before setting the flag to true.
eg:
function loadMoreResults() { if (flag) return; flag = true; [...] flag = false; }更多推荐
发布评论