jquery – 中止AJAX帖子

我的设置是这样的(为简洁起见,简化):
<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语句之前移动了注释1中的xhr,它可以工作,但AJAX请求仍在处理中.我的意思是在Firebug中,当我单击FB方法然后单击其他方法时,它显示如下:

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

但请求继续加载.

解决方法

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

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

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

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

var xhr = [];

$('.methods a').click(function(){
    // do something global to the anchors,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;
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...