[英]Prevent JQuery from firing multiple AJAX GET Request
I have this function 我有这个功能
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");
}
};
that makes an ajax request, how do I make sure it would only fire 1 ajax request? 这会发出ajax请求,如何确保它只会触发1个ajax请求? if a request has been already or sent. 如果请求已经或已经发送。 I do not want multiple ajax request. 我不想多个ajax请求。
scroll
event like the resize
event fires hundred times( depends on the browser ), you should use a plugin that provides a throttle
method like underscore.js or you can use setTimeout
function. scroll
事件(如resize
事件)触发一百次( 取决于浏览器 ),您应该使用提供throttle
方法的插件,例如underscore.js,或者可以使用setTimeout
函数。
An underscore.js throttle
example: underscore.js throttle
示例:
var throttled = _.throttle(scrollEvent, 500);
$(window).scroll(throttled);
An example using setTimeout
function: 使用setTimeout
函数的示例:
var timeout = '';
$(window).on('scroll', function(){
clearTimeout(timeout);
timeout = setTimeout(function(){
// Do something here
}, 300);
})
A related article by John Resig: http://ejohn.org/blog/learning-from-twitter/ John Resig的相关文章: http : //ejohn.org/blog/learning-from-twitter/
It is good idea to use throttled versions of event handlers for resize
and scroll
events. 最好使用事件处理程序的受限制版本来resize
和scroll
事件。 But to address your specific problem with making multiple request you can use the following code. 但是要解决发出多个请求的特定问题,可以使用以下代码。
var requestIsRunning; //Flag to indicate that there is a pending request.
function () {
if ($(window).scrollTop() >= ($(document).height() - $(window).height()) * 0.7) {
//do nothing if there is an active moreProfileComments request;
if(ruquestIsRunning) {return;};
requestIsRunning = 1;
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")
//when request is complete restore the flag
.always(function(){
requestIsRunning = 0;
});
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.