jquery - Javascript AJAX function returns undefined instead of truefalse - Stack Overflow

admin2025-04-21  0

I have a function that issues an AJAX call (via jQuery). In the plete section I have a function that says:

plete: 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 plete 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(){// plete});

I have a function that issues an AJAX call (via jQuery). In the plete section I have a function that says:

plete: 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 plete 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(){// plete});

Share Improve this question edited May 25, 2010 at 7:46 Anurag 142k37 gold badges222 silver badges261 bronze badges asked May 11, 2010 at 19:51 Josh KJosh K 28.9k20 gold badges88 silver badges132 bronze badges 2
  • can you show your callajax() function? Because what you are asking for should be the way you're already doing it :) – Pekka Commented May 11, 2010 at 20:08
  • @Pekka: It's a standard $.ajax() call, nothing special. I simply want to not have to modify it at all when deploying it to various applications. – Josh K Commented May 12, 2010 at 1:56
Add a ment  | 

1 Answer 1

Reset to default 7

plete is a callback function. It will be invoked by the Ajax object - asynchronously! - when the operation is plete. 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745172495a288744.html

最新回复(0)