如何防止多个Ajax请求

时间:2012-06-19 14:15:03

标签: jquery ajax json

我想向下滚动页面到某一点(#first_column DIV的高度),从服务器端获取json并将内容添加到#first_column。

现在问题是当我向下滚动到#first_column的高度时,几乎同时有很多Ajax调用。我想要的是向下滚动到#first_column的高度,调用服务器并获取json数据并将内容添加到#first_column。 #first_column的高度发生变化。然后我向下滚动到#first_column的高度将获得第二个Ajax请求。

有什么建议吗?

<script>
   $(window).scroll(function(){
   column_height = $("#first_column").height();
   screenTop = $(window).scrollTop();
   window_height = $(window).height();

if((screenTop+window_height)>=column_height){
      $.ajax({
            url: "/service/article_json.php",
            type: 'GET',
            async: false,
            cache: false,
            timeout: 30000,
            error: function(){
                return true;
            },
            success: function(data){ 
                $.each($.parseJSON(data), function(key,item) {

                  //Add content to #first_column

                });
            }
        });
  }
});

3 个答案:

答案 0 :(得分:5)

尝试使用标志,例如:

var ajaxInProgress = false;

$(window).scroll(function() {
  if(ajaxInProgress) return;
  ajaxInProgress = true;

  $.ajax({
    // setup here
    success: {
      // ...
      ajaxInProgress = false;
    },
    error: {
      // ...
      ajaxInProgress = false;
    }
  });
});

在此示例中,当ajaxInProgress设置为true window.scroll回调将简单地返回并且不执行任何操作,否则该标志将被设置为true,该调用将在{{1在success回调时,该标志将重置为error,这将允许另一个ajax调用。

答案 1 :(得分:3)

你可以在if语句中取消绑定事件,然后在Success方法中重新绑定它,如果你愿意的话。

$(window).unbind('scroll');

答案 2 :(得分:2)

var ajaxcallrunning;  //flag for ajax call

$(window).scroll(function() {

    if(ajaxcallrunning)
    {
      return;  // if a ajax call is running then return
    } 

    ajaxcallrunning = 1;      // otherwise set flag and execute ajax call

    $.ajax({
      // setup here
      success: {
         // ...
          ajaxInProgress = 0;    //reset flag after request complete
       },
       error: {
        // ...
         ajaxInProgress = 0;   //reset flag if error occurs
      }
    });
});
相关问题