繁体   English   中英

如何等待异步请求完成

[英]How to wait until the async request is complete

我有一个ajax注册表格。 用户可以在输入字段中输入所需的用户名,然后立即单击注册按钮,而ajax请求检查用户名是否可用尚未完成。 对于这种情况,我希望只有当ajax请求检查用户名完成时,注册按钮的操作才开始执行,否则请等待它完成然后继续。 这个怎么做?

我希望用户名验证功能保持异步,因为它每次用户在输入字段上键入内容时都会执行一次。

一种方法是在单击注册按钮时进入setTimeout()循环,并一直停留在该循环中,直到标志变为正确为止。 另一种方法是,如果请求未完成,则调用同步用户名检查请求。 有没有更好的方法?

如果您不使用jQuery给出答案,那就太好了。

不要为此使用setTimeout。

只需使用jquery的ajax的回调功能:在success回调或新done助手中执行“之后”代码:

$.ajax({
  url: "test.html"
}).done(function() { 
  // do things after the answer has been received
});

编辑:

没有jQuery,也没有立即触发:

var httpRequest = new XMLHttpRequest();
var requestDoneAndOK = false;
httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
                requestDoneAndOK = true;
        }               
    }
};
httpRequest.open('GET', url);
httpRequest.send();

然后,当单击“注册”按钮时,只需检查requestDoneAndOK ,如果它是真的,则调用其他函数。

编辑2:

一旦实现两个条件,便会执行代码:收到答案并单击注册按钮。

var registerClicked = false;
var ajaxAnswerReceived = false;
function check() {
    if (registerClicked && ajaxAnswerReceived) {
         // do the thing !
    }
}
var httpRequest = new XMLHttpRequest();
var requestDoneAndOK = false;
httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
              ajaxAnswerReceived = true;
                check();
        }               
    }
};
httpRequest.open('GET', url);
httpRequest.send();
document.getElementById('registerButton').onclick = function(){
     registerClicked = true;
     check();
};

如果您要在没有jQuery的情况下执行此操作,则需要使用默认的JavaScript调用机制onreadystatechange。 请记住,jQuery只是默认机制的包装。 我确实建议您使用jQuery或其他方式来防止整个交叉浏览器问题和HTTP状态更改逻辑。

在此处阅读有关本机内容的所有信息: http : //www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

您需要使用回调和存储验证标志布尔值,然后在用户提交注册页面之前检查它们。 这是一个jQuery实现,但是将其转换为常规js并不困难。 该方法在这里定义:

var goodUsername = false;

// keyup handler, pseudo code 
$('#username').keyup(function(event) { 
    // perform the username validation with an ajax call:
    $.ajax({
        url: "validateUsername.php"
    }).done(function(data) {
        // set the goodUsername if its good or not
        if (data.usernameIsGood)
            goodUserName = true;
    });
});

// submit the registration form only if the username has been checked and is good
$('#registrationFormButton').click(function(event){
     if (goodUsername)
         return true; // allows the browser to submit the form
     else
         return false;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM