Ajax的意思是“异步JavaScript和XML”,因此它不会等待$ .post完成,而只是在你的代码中继续。
要解决此问题,您必须使用回调函数:
jQuery.post(url [,data] [,success(data,textStatus,jqXHR)] [,
dataType])
url包含发送请求的URL的字符串。
data使用请求发送到服务器的映射或字符串。
success(data,textStatus,jqXHR)执行的回调函数
如果请求成功。
dataType服务器所需的数据类型。默认:
智能猜测(xml,json,script或html)。
样品:
function usernameCheck(){
$.post("http://omnicloud.me/signup",
{username: $("#username").val()},
function(response){
if(response=="true"){
$('#passAlert').html("Sorry, that username is already taken")
}
});
}
您也可以传递匿名回调:
function usernameCheck(successCallback){
$.post("http://omnicloud.me/signup",
{username: $("#username").val()},
function(response){
if(response=="true") successCallback();
});
}
// Somewhere else in your code:
usernameCheck(function(){
$('#passAlert').html("Sorry, that username is already taken")
});