防止JQuery触发多个AJAX GET请求

时间:2013-03-17 07:35:25

标签: javascript jquery ajax

我有这个功能

 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请求。

2 个答案:

答案 0 :(得分:3)

scroll事件如resize事件触发数百次(取决于浏览器),您应该使用提供throttle方法的插件{ {3}}或者您可以使用setTimeout功能。

一个下划线.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撰写的相关文章: underscore.js

答案 1 :(得分:2)

最好为resizescroll事件使用受限制的事件处理程序版本。但是为了解决您提出多个请求的具体问题,您可以使用以下代码。

 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;
          });

     }
 };
相关问题