且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript AJAX函数返回undefined而不是true / false

更新时间:2022-10-15 18:00:35

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.