我有这个功能
$.fn.validate.checkValidationName = function(id) {
$.post("PHP/submitButtonName.php", {checkValidation: id},
function(data) {
if(data.returnValue === true) {
name = true;
} else {
name = false;
}
**console.log("name = "+name); **//this prints out "true"****
}, "json");
};
这个调用它的.click函数。所有变量都在此函数外部声明,以便其他函数可以访问它们
$('.submitBtn').click(function() {
//clears the array before re-submitting the click function
nameValues = [];
usernameValues = [];
emailValues = [];
name = false;
username = false;
email = false;
//for each of the input tags
$("input").each(function() {
//if the curent input tag has the class .name, .userpass, or .email
if(($(this).hasClass("name"))) {
nameValues.push($(this).val());
} else if(($(this).hasClass("userpass"))) {
usernameValues.push($(this).val());
} else if(($(this).hasClass("email"))) {
emailValues.push($(this).val());
}
});
//call the checkValidation function with the array "values"
$.fn.validate.checkValidationName(nameValues);
$.fn.validate.checkValidationUsername(usernameValues);
$.fn.validate.checkValidationEmail(emailValues);
console.log("name = "+name); //but this prints out "false"
console.log("username = "+username);
console.log("email = "+email);
if((name === "true") && (username === "true") && (email === "true")) {
alert("Everything checks out great");
} else {
alert("You missed one!");
}
});
当我单击链接以触发第一个函数时,它在函数内部将值返回为“ true”,但是当我在函数调用后在.click函数中使用
console.log("name"+name);
时,它将输出false。为什么是这样?我是否需要从checkValidatoinName函数返回某些内容?
最佳答案
$.post
是异步的,这意味着它在继续操作之前不会等待结果返回。您可能正在某个地方将name
初始化为true
,并且它是第一次获取true
,但在其他所有情况下,它都是false
,因为从第一个开始的AJAX已完成并将其设置为false
。
尝试使用$.ajax
代替$.post
,然后在选项中将async
设置为false
。 $.post
documentation显示$.post
提供给$.ajax
的选项。