gpt4 book ai didi

javascript - 防止 JQuery 触发多个 AJAX GET 请求

转载 作者:行者123 更新时间:2023-11-30 08:53:45 26 4
gpt4 key购买 nike

我有这个功能

 function () {
if ($(window).scrollTop() >= ($(document).height() - $(window).height()) * 0.7) {
//$(window).unbind('scroll');

jQuery.get('moreProfileComments', function (e, success) {
$(window).scroll(scrollEvent);
console.log(e);
var result_div = $(e).find('#user_comments #u_cont div');
var original_div = $('#user_comments #u_cont div');

if (result_div.last().html() === original_div.last().html()) {
//alert("TEST");
//$(window).unbind('scroll');
} else {
//$(rs).appendTo('#search_results').fadeIn('slow');
$('#user_comments #u_cont').append($(e).find('#user_comments #u_cont').html());
$(window).scroll(scrollEvent);
}
}, "html");

}
};

发出 ajax 请求,我如何确保它只会触发 1 个 ajax 请求?如果请求已经或已发送。我不想要多个 ajax 请求。

最佳答案

scroll 事件,例如 resize 事件会触发数百次(取决于浏览器),您应该使用提供 throttle 方法,如 underscore.js或者您可以使用 setTimeout 函数。

underscore.js throttle 示例:

var throttled = _.throttle(scrollEvent, 500);
$(window).scroll(throttled);

使用setTimeout 函数的例子:

var timeout = '';
$(window).on('scroll', function(){
clearTimeout(timeout);
timeout = setTimeout(function(){
// Do something here
}, 300);
})

John Resig 的相关文章: http://ejohn.org/blog/learning-from-twitter/

关于javascript - 防止 JQuery 触发多个 AJAX GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15458558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com