Javascript的AJAX功能收益不确定,而不是真/假

问题描述:

我有发出AJAX调用(通过jQuery)的函数。在完整部分我有一个函数,上面写着:

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.

如果我把一个警报(textStatus)完整功能我得到真正的,但不是说功能之前,返回未定义

If I put an alert(textStatus) in the complete function I get true, but not before that function returns undefined.

这将有可能通过一个回调函数来我 callajax()的方法?像:

Would it be possible to pass a callback function to my callajax() method? Like:

callajax(函数(){//成功},功能(){//错误},功能(){//完成});

完整回调的功能。它将由Ajax对象调用 - 异步! - 操作完成时。有没有办法让你赶上回调的结果,只有在Ajax对象能做到这一点。

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.

callajax()功能 - 你不可见的功能,但我认为它只是使Ajax调用 - 无法返回调用的结果(=的响应头和身体),作为呼叫将不会被说完呢,当你退出 callajax()的功能。

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.

更新:它的的也很可能使同步AJAX调用。感谢@Andris指出这一点。在jQuery中,您需要将异步选项设置为:文档的此处。然而,即使是那些使用标准的回调函数,据我所看到的,所以你想要回国的方法仍可能无法正常工作。

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.