gpt4 book ai didi

jquery - 中止 AJAX 发布

转载 作者:行者123 更新时间:2023-12-01 06:57:23 28 4
gpt4 key购买 nike

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

<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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com