中止AJAX帖子

Hen*_*son 1 ajax jquery

我的设置是这样的(为简洁起见,简化):

<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 -->
Run Code Online (Sandbox Code Playgroud)

因此,每个方法(如果单击)将淡入内联内容,但具有"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;
});
Run Code Online (Sandbox Code Playgroud)

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

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

// ajax request xhr - keeps on loading
// ajax request xhr aborted
Run Code Online (Sandbox Code Playgroud)

但请求继续加载.

Jos*_*eti 5

当单击事件发生时,您的xhr变量在调用的函数内是本地的.

当您调用abort方法时,xhr不是用于post方法的变量.

xhr变量需要在绑定到click事件的函数外部,否则在检查其他单击事件时它将是未定义的.

此外,由于您可能需要多个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;
});
Run Code Online (Sandbox Code Playgroud)