如何清除旧的ajax请求

时间:2013-09-30 09:29:48

标签: php ajax wordpress jquery

我正在尝试编写用于在Scroll上获取产品的代码 我喜欢的步骤如下 1]搜索产品 2]在一个div上获得结果 3]并且在结果div的滚动上想要下一个产品

但每次搜索和滚动产品时会发生什么 一次调用许多ajax请求 我只想要一次ajax应该调用(而不是旧的ajax请求)

我的jQuery代码是

 jQuery("#product_search_filter").submit(function () {
   jQuery(".load_more_result").remove();
    jQuery.ajax({
        url: ajaxurl,
        type: "post",
        data: jQuery(this).serialize(),
        dataType: "json",
        success: function (products) {
            var load_more = 0;
            jQuery(".right_bar_sub_inner").html("");
            jQuery.each(products, function (i, data) {
                if (this.image) {
                    jQuery(".right_bar_sub_inner").append('<div class="product_show" alt="' + i + '"> <img class="right_bar_img size-auto" src="' + this.image + '" title="'+ this.title +'"> </div>');
                }
            });
            jQuery(".right_bar_sub_inner").append("<div class='load_more_result'>Load More...</div>");
            var start = false;

            jQuery(".right_bar_sub").scroll( function(){
                var _data = jQuery("#product_search_filter").serialize();
                _data += "&offset=" + load_more;
                jQuery(".load_more_result").css('opacity','0.1');                                            
                jQuery.ajax({
                    url: ajaxurl,
                    type: "post",
                    data: _data,
                    dataType: "json",
                    success: function (products) {
                        jQuery.each(products, function (i, data) {
                            if (this.image) {
                                jQuery(".load_more_result").before('<div class="product_show" alt="' + i + '"> <img class="right_bar_img size-auto" src="' + this.image + '" title="'+ this.title +'"> </div>');
                            }
                        });
                        jQuery(".load_more_result").css('opacity','1');
                        start = false;
                    }
                });
                return false;
            });
        }
    });
    return false;
});

你可以看到这个问题 Lamp-database

尝试再次搜索然后在firebug的控制台上查看 你可以看到第一次只有一个请求正在调用滚动 如果再次搜索,则两个请求正在调用

和 所以...

1 个答案:

答案 0 :(得分:0)

您可能想要的是不在每个滚动事件上发出ajax请求,而是在用户停止滚动一段时间后发出ajax请求。为此,您可以在每个滚动事件上重新启动计时器,在达到特定值(示例中为250毫秒)后将触发实际的ajax请求。

e.g。你可以 在每个滚动调用scrollled()

var timeoutid;
jQuery(".right_bar_sub").scroll( function() {
  scrolled();
  //...
});

function scrolled() { //delay the request. 
  clearTimeout(timeoutid); //otherwise it will be called multiple times
  timeoutid=window.setTimeout("ajaxcall()", 250); //make ajax request in 250 ms
}

function ajaxcall() {
 //make your ajax request here
}
相关问题