我有这个代码:我的第一个验证是我试图检查用户名是否为null然后我有一个ajax验证,验证用户名是否已经存在。但是,当我尝试在回调函数中分配我的变量时,我指定的值不起作用..
isValid
初始值为true
..如果username
存在,我想在其上分配false
..但值不会改变..
当我尝试console.log(isValid)
时,它仍然是真的..在此先感谢..
function validateStep1(){
var isValid = true;
// Validate Username
var un = $('#username').val();
if(!un && un.length <= 0){
isValid = false;
$('#msg_username').html('(Please fill username)').show();
}else{
//username ajax validation
var $check_username;
var $form = $('#create_user_form').data('url');
var $url = $form + "employee_c/username_validation";
$.when(ajax_validation($url,un)).done(function(){
if(_gbValidateSuccess){
$('#msg_username').html('(Username is already existing!)').show();
isValid = false;
}else{
$('#msg_username').html('').hide();
}
});
}
console.log(isValid); //still true.. but should be false instead..
}
答案 0 :(得分:0)
使用Promise,它非常简单,非常适合异步调用(下载并包含promise js)
-module(macro_mod_names).
-define(SERVER, ?MODULE). % Oh, god! Why??
-define(TM, another_module).
-export([bad/1, good/1]).
bad(Arg) ->
Parsed = gen_server:call(?SERVER, {parse, Arg}),
?TM:handle(Parsed).
good(Arg) ->
Parsed = gen_server:call(?MODULE, {parse, Arg}),
another_module:handle(Parsed).
//为promise js添加此代码
function validateStep1(){
return new Promise(function (resolve, reject) {
var un = $('#username').val();
if(!un && un.length <= 0){
reject(); // it will return false
$('#msg_username').html('(Please fill username)').show();
}else{
//username ajax validation
var $check_username;
var $form = $('#create_user_form').data('url');
var $url = $form + "employee_c/username_validation";
$.when(ajax_validation($url,un)).done(function(){
if(_gbValidateSuccess){
$('#msg_username').html('(Username is already existing!)').show();
isValid = false;
reject(); // it will return false
}else{
$('#msg_username').html('').hide();
resolve(); //it will return true
}
});
}
});
}