【问题标题】:abort AJAX post中止 AJAX 帖子
【发布时间】:2011-11-25 19:39:38
【问题描述】:

我的设置是这样的(为清楚起见进行了简化):

<div class="methods">
    <a href="#a">Method 1</a>
    <a href="#b" class="fb_method">FB Method</a>
    <a href="#c">Method 3</a>
</div>

... <!-- contents -->

因此,如果单击,每个方法都会淡入内联内容,但具有“fb_method”类的锚除外,因为它需要先执行 AJAX 请求,然后才能附加到内容中的内容容器。

所以我的 jQuery 是这样的:

$('.methods a').click(function(){
    // do something global to the anchors, eg : change the bg color, etc
    // set the target container
    var target = $(this).attr('href');
    var xhr;

    //if user clicks fb_method buttons
    if($(this).hasClass('fb_method')){
        //do ajax request - NOTE 1
        xhr = $.post("/ajax/get_fb_albums.php",function(msg){                           
            $(target).html('').append(msg).fadeIn();
        });
    }else{
        //abort all ajax request
        xhr.abort();
        $(target).fadeIn();
    }
    return false;
});

所以我想要的是当用户第一次点击 fb_method 按钮时,它会请求一个 AJAX。但是如果他们突然改变主意,点击其他方法,我想中止之前的AJAX请求。

我通过 Firebug 对其进行了跟踪,它返回了 xhr 未定义的错误。如果我在 if 语句之前移动了 NOTE 1 中的 xhr,它可以工作,但 AJAX 请求仍在处理中。我的意思是在 Firebug 中,当我单击 FB 方法然后单击其他方法时,它会显示如下内容:

// ajax request xhr - keeps on loading
// ajax request xhr aborted

但是请求一直在加载。

【问题讨论】:

  • 也许你需要将 xhr 声明为全局变量

标签: jquery ajax


【解决方案1】:

您的 xhr 变量在点击事件发生时调用的函数内是本地的。

调用 abort 方法时,xhr 不是用于 post 方法的变量。

xhr变量需要在绑定点击事件的函数之外,否则在查看其他点击事件时会未定义。

此外,由于您可能需要多个 xhr 变量来存储不同的帖子,因此您应该创建一个数组或对象来存储不同的帖子。

var xhr = [];

$('.methods a').click(function(){
    // do something global to the anchors, eg : change the bg color, etc
    // set the target container
    var target = $(this).attr('href');

    //if user clicks fb_method buttons
    if($(this).hasClass('fb_method')){
        //do ajax request (add the post handle to the xhr array)
        xhr.push( $.post("/ajax/get_fb_albums.php", function(msg) {                           
            $(target).html('').append(msg).fadeIn();
        }) );
    }else{
        //abort ALL ajax request
        for ( var x = 0; x < xhr.length; x++ )
        {
            xhr[x].abort();
        }
        $(target).fadeIn();
    }
    return false;
});

【讨论】:

  • 你应该也清除数组,还是一旦中止请求对象就不会存储中止的请求对象?
猜你喜欢
  • 1970-01-01
  • 2021-10-16
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
相关资源
最近更新 更多