微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript检查表单,而不是等待AJAX​​响应

这是我表格中支票的一部分

function check(theform) {
var re = /^\w[0-9A-Za-z]{5,19}$/;
if (!re.test(theform.username.value)) { 
    alert("not valid username");
    theform.username.focus();
    return false;
}

$.ajax({
    type: "POST",
    url: "username.asp",
    data: "username="+theform.username.value,
    success: function(msg){
        username = msg;
        if (!username) {
            alert("username already in use");
            return false;
        }
    }
});

var re = /^\w[0-9A-Za-z]{5,19}$/;
if (!re.test(theform.password.value)) { 
    alert("not valid password");
    theform.password.focus();
    return false;
}
}

出于某种原因进行同步…它检查用户名,然后用ajax复制用户名,而不是等待响应并跳转密码检查.

我不想将其余的代码插入到isreadystate(或者它是什么),因为我可能会将用户名重复检查移动到最后……然后函数将在ajax之前结束

我该怎么办?

解决方法:

AJAX中的第一个A代表“Asynchonous”.进行呼叫,并且继续执行该功能而不等待呼叫返回.

您可以将调用中的async选项设置为false,使您的呼叫同步.但是,您必须更改函数,以便返回false使其通过check函数,并且jQuery手册不建议:

The first letter in Ajax stands for “asynchronous,” meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.

更好的方法是在函数内“实时”进行检查,然后启动Ajax请求,并在该请求的成功回调中提交表单.

第二次尝试同步通话.这似乎确实有效 – 在FF 3.6中测试过.

var name_success = true;

$.ajax({
    type: "POST",
    async: false,
    url: "username.asp",  // Needs to return "EXISTS" in this example 
    data: "username="+theform.username.value,
    success: function(msg){
        username = msg;
        if (username == "EXISTS") {  // Changed callback return value - 
                                     // safer this way
            alert("username already in use");
            name_success = false;   // should work because
                                    // we're in check()'s scope
            return false;
        }
    }
});

alert (name_success);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐