jquery函数不能正确返回值

时间:2010-02-08 02:00:43

标签: javascript jquery

我有这个功能

$.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函数返回一些内容?

1 个答案:

答案 0 :(得分:2)

$.post是异步的,这意味着它不会等待结果在继续之前返回。您可能正在某处初始化nametrue,并且第一次获得true,但所有其他时间,它都是false,因为来自第一次的AJAX完成并将其设置为false

尝试使用$.ajax代替$.post,并在选项中将async设置为false$.post documentation显示$.post将为$.ajax提供的选项。