第一个简单通用的解决方案 - 使用同步调用:
jQuery.ajax({
type:"GET",
async: false,
...
在这种情况下,浏览器将等待调用完成。但它有时会导致页面冻结(在等待时)
第二种解决方案是使用自定义标志/属性,尽管您讨厌它(查看in_progress属性):
jQuery(function () {
jQuery('.school_activity').click(function () {
if( $(this).attr('in_progress') ) return;
link = jQuery(this);
p_type = link.attr('p_type');
o_type = link.attr('o_type');
jQuery('.i-link a').removeClass('stream_wall_select');
$(this).attr('in_progress', 1);
var link = this;
jQuery.ajax({
type:"GET",
url:'<%= some_path(@school) %>',
data:'format=js&p_type=' + p_type + '&tagged_type=' + o_type,
success:function (response) {
jQuery('#s_activity_div').html(response);
},
complete: function(){ $(link).removeAttr('in_progress'); }
});
})
})
为了使它成为一个健壮和通用的解决方案,我们可以为这种情况创建一个自定义函数:
function waCall( element, ajaxParams, beforeAjaxCallback, afterAjaxCallback ) {
if( $(element).attr('in_progress') ) return;
var link = $(element);
$(link).attr( 'in_progress' );
ajaxParams['complete'] = function() { $(link).removeAttr('in_progress');
if( afterAjaxCallback ) afterAjaxCallback( link ); };
if( beforeAjaxCallback ) beforeAjaxCallback(link);
$.ajax( ajaxParams );
}
jQuery(function () {
jQuery('.school_activity').click(function () {
waCall( this, {
type:"GET",
url:'<%= some_path(@school) %>',
data:'format=js&p_type=' + p_type + '&tagged_type=' + o_type,
success:function (response) {
jQuery('#s_activity_div').html(response);
}
}, function(link) {
var p_type = link.attr('p_type');
var o_type = link.attr('o_type');
jQuery('.i-link a').removeClass('stream_wall_select');
}
}
});