2010-02-08 214 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