我想在jquery
中再次调用相同的ajax请求时避免以前的ajax请求<input type="text" id="username" onkeyup = "userName(this)" >
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();
}
}
});
}
答案 0 :(得分:2)
您可以使用.abort()
<input type="text" id="username" onkeyup = "userName(this)" >
<script>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();
}
});
}</script>
使用$ .post代替$ .ajax,因为它是简化的$ .ajax的缩写形式
答案 1 :(得分:0)
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;
}
});
}