jquery - 中止 AJAX 发布

标签 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”类的 anchor ,因为它需要先执行 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 未定义的错误。如果我将注释 1 中的 xhr 移到 if 语句之前,它可以工作,但 AJAX 请求仍在处理中。我的意思是在Firebug中,当我单击FB方法然后单击其他方法时,它显示如下内容:

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

但请求仍在加载。

最佳答案

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

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

xhr 变量需要位于绑定(bind)点击事件的函数外部,否则当您检查其他点击事件时,该变量将是未定义的。

此外,由于您可能需要多个 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;
});

关于jquery - 中止 AJAX 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7565798/

相关文章:

jquery - 使用 AJAX 的 phpseclib 实时控制台/终端

php - 将带有ajax的数组传递给php文件

c# - 如果用户将复选框设置为 true,如何动态显示上传按钮?

javascript - 如何向 Fancy Box Loader 添加文本

javascript - 外部文件中未触发点击事件

javascript - Jquery 通过 ajax 设置 HTML

php - Drupal 可扩展悬停菜单

jquery keyup 事件取决于 id 参数

javascript - 由于 CORS,无法对 BigCommerce API 进行身份验证

php - Ajax表单多次提交。有时