Javascript AJAX函数返回undefined而不是true / false [英] Javascript AJAX function returns undefined instead of true / false
问题描述
我有一个函数发出AJAX调用(通过jQuery)。在 complete
部分中,我有一个函数说:
complete: function(XMLHttpRequest,textStatus)
{
if(textStatus ==success)
{
return(true);
}
else
{
return(false);但是,如果我这样调用:
<$> p>
if(callajax())
{
//做某事
}
else
{
//其他
}
如果我在完成中设置了警报(textStatus)
/ code>函数我得到真,但不是之前该函数返回 undefined
。
是否可以将回调函数传递给我的 callajax()
方法?像:
callajax(function(){// success},function(){// error},function });
解决方案 a 回调功能。它将被Ajax对象异步调用! - 操作完成时。没有办法捕获回调的结果,只有Ajax对象可以这样做。
您的 callajax()
function - 你不显示那个函数,但我认为它只是使Ajax调用 - 不能返回调用的结果(=响应头和正文),因为调用将不会完成,当你退出 callajax()
函数。
更新:也很可能进行同步AJAX调用。感谢@Andris指出这一点。在jQuery中,您需要将 async
选项设置为 false
:Docs 此处。但是,即使是那些使用标准的回调函数,只要我能看到,所以你想要的方法返回 false
或 true
可能仍然不工作。
I have a function that issues an AJAX call (via jQuery). In the complete
section I have a function that says:
complete: function(XMLHttpRequest, textStatus)
{
if(textStatus == "success")
{
return(true);
}
else
{
return(false);
}
}
However, if I call this like so:
if(callajax())
{
// Do something
}
else
{
// Something else
}
The first is never called.
If I put an alert(textStatus)
in the complete
function I get true, but not before that function returns undefined
.
Would it be possible to pass a callback function to my callajax()
method? Like:
callajax(function(){// success}, function(){// error}, function(){// complete});
解决方案 complete
is a callback function. It will be invoked by the Ajax object - asynchronously! - when the operation is complete. There is no way for you to catch the callback's result, only the Ajax object could do that.
Your callajax()
function - you're not showing that function but I assume it simply makes the Ajax call - can not return the call's result (= the response headers and body), as the call will not have been finished yet when you exit the callajax()
function.
Update: It is also well possible to make synchronous AJAX calls. Thanks to @Andris for pointing this out. In jQuery, you need to set the async
option to false
: Docs here. However, even those use the standard callback functions as far as I can see, so your desired method of returning false
or true
may still not work.
这篇关于Javascript AJAX函数返回undefined而不是true / false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!