Ajax无限滚动功能发射两次。(Ajax infinite scroll feature firing twice.)

编程入门 行业动态 更新时间:2024-10-24 15:21:11
Ajax无限滚动功能发射两次。(Ajax infinite scroll feature firing twice.)

出于某种奇怪的原因,下面的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; }

更多推荐

本文发布于:2023-07-31 00:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340369.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   功能   Ajax   infinite   firing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!