使用jquery ajax返回true时没有回调 [英] use jquery ajax don't have callback when return true
问题描述
我尝试使用查询ajax,当我返回false"时,我也会得到回调
I try use query ajax and when I have "return false" I get callback as well
$(document).ready(function(){
$("form#Form").submit(function(){
$.ajax({
url: "ajax.php",
type: "POST",
data: $(this).serialize(),
success: function(callback){
alert(callback);
} //success
}); //ajax
return false;
}); //submit
}); //ready
在php文件中,我只是回显"dennis",它起作用并且我收到内容"dennis"的警报. 当我尝试这样的事情时:
in the php file I just echo "dennis", it works and I get alert with content "dennis". when I try something like this:
$(document).ready(function(){
$("form#Form").submit(function(){
$.ajax({
url: "ajax.php",
type: "POST",
data: $(this).serialize(),
success: function(callback){
alert(callback);
} //success
}); //ajax
if (callback == "dennis"){
return false;
}else{
return true;
}
}); //submit
}); //ready
我得到空警报,并且表单的行为就像他得到返回真"一样. 我也尝试把变量放回去,但还是一样..
I get empty alert and the form act like he get "return true". I also try put variable and return him, but still same problem..
为什么会这样?如何解决?
why it happened? how fix it?
推荐答案
这是因为ajax-scope将异步执行,因此当您检查if (callback == "dennis")
时,您的ajax调用 may 甚至都没有达到您的php,因此回调将为 undefined .
This is because the ajax-scope will execute asynchronous, hence when you check if (callback == "dennis")
, you ajax call may not even reached your php yet, therefore callback will be undefined.
您需要在成功范围内检查callback
(它实际上是一个错误的变量名,因为它不是回调,而是ajax调用的结果).
You need to check callback
(it's actually a bad variable name as it is not a callback, but a result from your ajax-call) in the success scope.
$.ajax({
url: "ajax.php",
type: "POST",
data: $(this).serialize(),
success: function(callback){
alert(callback);
if (callback == 'dennis') {
return true;
} else return false;
} //success
}); //ajax
现在,您的下一个问题是您的表单可能已经返回true,因此与在此处返回true | false相比,用结果调用新函数更好.
Now, your next problem is that your form probably already returns true, so better calling a new function with your result, than returning true|false here.
// ajax metod success function
success: function(result){
alert(callback);
onFormReturn(result);
} //success
并定义处理结果的功能
// elsewhere, outside ajax-scope - even outside document.ready
function onFormReturn(result) {
if (result == "dennis") {
// do your stuff
} else {
// do something else
}
}
这篇关于使用jquery ajax返回true时没有回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!