2010-02-08 217 views
0

我有这个功能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"); 
}; 

,并调用它。点击此功能。所有的变量都这个函数外声明,以便他们应该可以访问其他功能

$('.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!"); 
} 
}); 

当我点击链接触发第一个函数,它返回的值是“真”里面的功能,但是当我console.log("name"+name);在函数调用后的.click函数中打印出false。

这是为什么?我需要从checkValidatoinName函数返回一些东西吗?

回答

2

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

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

+0

那么我会如何解决这个问题?我可以做到这一点,所以我的.click函数会运行,然后立即运行另一个函数? – Catfish 2010-02-08 03:40:42

+0

我编辑了我的答案,以显示如何使AJAX请求同步而不是异步。 – icktoofay 2010-02-08 04:09:13

+0

尝试使用$ .ajax和async:false。仍然没有办法。 – Catfish 2010-02-08 07:13:17