jquery ajax请求之前,避免在jQuery中再次调用同一个Ajax请求之前的Ajax请求(Avoid previous aj...

我想避免对jQuery中再次调用同一个Ajax请求之前的Ajax请求

function userName(e) {

$.ajax({

type:"POST",

url:BasePath + "/users/userName",

data:"name=" + $.trim($(e).val()),

success:function (resp) {

if (resp == 1) {

$('#div.error_message').html('Username already taken...').show();

} else {

$('#div.error_message').hide();

}

}

});

}

Answer 1:

您可以使用.abort()

var xhr=null;

function userName(e) {

if(xhr)xhr.abort();//first time it will not be aborted

xhr=$.post(BasePath + "/users/userName",{"name": $.trim($(e).val())},function (resp) {

if (resp == 1) {

$('#div.error_message').html('Username already taken...').show();

} else {

$('#div.error_message').hide();

}

});

}

代替$就使用.post的$,因为它简化和$就短期形式

Answer 2:

var ajaxReq;

function userName(e) {

if(ajaxReq){

ajaxReq.abort();

//OR you may return from here as

//another request is already in progress

}

ajaxReq = $.ajax({

type:"POST",

url:BasePath + "/users/userName",

data:"name=" + $.trim($(e).val()),

success:function (resp) {

if (resp == 1) {

$('#div.error_message').html('Username already taken...').show();

} else {

$('#div.error_message').hide();

}

ajaxReq=null;

}

});

}

文章来源: Avoid previous ajax request on calling the same ajax request again in jquery