How to return value when AJAX request is succeeded

This question already has an answer here:

  • How do I return the response from an asynchronous call? 33 answers

  • You should set parameter async to false . Try this code:

    function ajaxRefresh(actionUrl) {
        var succeed = false;
    
        $.ajax({
        async: false,
        url: actionUrl,
        success: function() {
             succeed = true;
        }});
    
        return succeed;
    }
    

    You can refactor your code a little bit so that your success callback triggers the next operation that depends on the true/false result. For example, if you currently have something like:

    function main() {
      // some code
    
      if (ajaxRefresh(url)) {
        // do something
      }
    }
    

    You would change that to something like:

    function main() {
      // some code
    
      ajaxRefresh(url);
    }
    
    function doSomething(successFlag) {
      if (successFlag) {
        // do something
      }
    }
    
    function ajaxRefresh(actionUrl) {
      $.ajax({
             url: actionUrl,
             success: function() {
               doSomething(true); // or false as appropriate
             }});
    }
    

    You could also put the if test into the ajax callback function instead of in the doSomething() function. Up to you.

    Or you can make a synchronous request, and figure out the ajaxRefresh() function's return value after the request is done. I would not recommend that for most purposes.


    You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.

    Solution 1

    function ajaxRefresh(actionUrl, successCallback) {
        $.ajax({
           url: actionUrl,
           success: successcallback
        });
    }
    

    But there's a workaround: Just add a callback parameter to the function. This function will be executed when the request has finished.

    Solution 2

    You can return a jquery deferred.

    function ajaxRefresh(actionUrl, successCallback) {
        return $.ajax({
           url: actionUrl
        });
    }
    

    Now you can use the function like:

    function otherFunction()
    {
         ajaxRefresh().success(function() {
            //The ajax refresh succeeded!
         }).error(function() {
            //There was an error!
         });
    }
    

    For more information about jquery deferreds look at http://www.erichynds.com/jquery/using-deferreds-in-jquery/.

    链接地址: http://www.djcxy.com/p/9494.html

    上一篇: 如何正确返回jQuery ajax成功函数的数组?

    下一篇: AJAX请求成功时如何返回值