【发布时间】: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 声明为全局变量