2

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();
        }
        }
    });
}
4

2 に答える 2

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>

$.ajaxの簡略化された短縮形である$.ajaxの代わりに$.postを使用します

于 2012-05-19T06:28:51.497 に答える
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;
        }
    });
}
于 2012-05-19T06:28:50.913 に答える