我目前的代码:
else{
$.post("ajax/ajax_login.php",
{register_username : $(selector).val()}
,function(ajax_data){
if(ajax_data == 0){
output_error(selector, "is already taken.");
return false;
}
});
output_error(selector, 0);
return true;
}
正如您所看到的,我正在使用$ .post来查看是否已经使用了用户名。如果它被采用,ajax.php文件将返回值0. if(ajax_data == 0)将为真。
我的问题:在if语句中我想返回false,然后不继续。但它继续从$ .post中继续,并且还隐藏了我的输出。
有没有办法打破这个$ .post而不是继续下面的代码。 (我甚至认为下面的代码在$ .post代码之前执行)
答案 0 :(得分:1)
Ajax调用是异步的,所以,是的,$.post()
之后的代码确实在POST完成之前执行。使用以下内容更改完成处理程序:
if (ajax_data == 0)
output_error(selector, "is already taken");
else
output_error(selector, 0);
请注意,您无法确定调用函数将返回什么,因为它已经完成执行。如果你需要传回一些东西,你也需要设置一个回调:
function doSomethingWhichRequiresAPost(some_parameter,callback)
{
// ... some other stuff ...
$.post("ajax/ajax_login.php",
{register_username : $(selector).val()},
function(ajax_data)
{
if (ajax_data == 0)
{
output_error(selector, "is already taken.");
callback(false);
}
else
{
output_error(selector, 0);
callback(true);
}
}
);
}
现在,不是调用你的函数并检查它的返回值来做某事:
if (doSomethingWhichRequiresAPost(parameter))
// stuff to do if true
else
// stuff to do if false
你传递回调:
doSomethingWhichRequiresAPost(parameter,function(ret)
{
if (ret)
// stuff to do if true
else
// stuff to do if false
}
);