最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ajax - javascript function return value confusion - Stack Overflow

programmeradmin4浏览0评论

I'm unclear about return value of the following dummy code:

function foo()
  var ret = 0;
  var xhr=send_request( "bla", function() {
      // do something with the AJAX response
      // based on the value of response, var ret get set
  } );
  return ret;
}

What I would like to achieve is that: based on the AJAX response, I might decide to try the request again. But the function above always returns 0 regardlessly.

Apparently I can make the foo() function decide to call send_request() twice when needed but it's a bit ugly. Is there a easy and nice way to do this?

Thanks

I'm unclear about return value of the following dummy code:

function foo()
  var ret = 0;
  var xhr=send_request( "bla", function() {
      // do something with the AJAX response
      // based on the value of response, var ret get set
  } );
  return ret;
}

What I would like to achieve is that: based on the AJAX response, I might decide to try the request again. But the function above always returns 0 regardlessly.

Apparently I can make the foo() function decide to call send_request() twice when needed but it's a bit ugly. Is there a easy and nice way to do this?

Thanks

Share Improve this question asked Jun 13, 2011 at 15:09 lang2lang2 12k21 gold badges90 silver badges137 bronze badges 2
  • What is foo returning to? Can that be accessed within send_request? – Jeremy Commented Jun 13, 2011 at 15:12
  • your ajax callback function is called asynchronously thus ret will never get set to something different. the scope of the unnamed function is not in foo() but local. – venimus Commented Jun 13, 2011 at 15:15
Add a ment  | 

4 Answers 4

Reset to default 7

You are trying to make the ajax call synchronously, but you are a making an asynchronous call.

It is important to understand that the way you have it written, the code does not wait for the AJAX call to finish before moving on to the next line. Therefore, it always returns the initial value of ret.

Do several things to fix this:

  • Use jQuery (if you are not already)
  • Use jQuery's ajax() function, and set async to false.

Should look something like this:

function foo()
    var ret = $.ajax({ url: "blah",
                       async: false
                     }).responseText;

    // do your stuff here

    return ret;
}

EDIT: It is possible to do this with an asynchronous call, but you have to adjust the way you think about the problem. Rather than thinking about return values, you have to think about callback functions.

For the sake of example, lets say I'm trying to get the user's name and put it on the page. My code would look something like this:

function GetUsername() {
    $.ajax( { url: "blah",
              success: PopulateUsername    // Specify a callback
            });
    // I don't do anything else. Execution will continue when the
    // callback gets called from the AJAX call.
}

function PopulateUsername(data) {
    alert(data);
    // Anything else I want to do, I do here, because it is only 
    // here that I have access to the result.
}

GetUsername();  // I call GetUsername() here, and that's it. Any
                // further actions that need to happen are going to
                // occur in the callback function

the variable ret has a local scope within the function. Therefore, each time you call it, the variable gets initialized to 0.

Moreover, when the function is returning the variable ret, the send_request function (which set something else to ret) has not run yet due to which the value returned is always 0. It must be after the function got returned that the ajax request gets pleted and the send_request function set a new value to ret.

If you want to keep things synchronous, then use Stargazer712's suggestion.

You could try keeping things asynchronous with something like this:

function foo(callback)
  var xhr=send_request( "bla", function(result) {
     callback(result)
  } );
}


function test(result) {
  // test result here 
  if(result != "what I want")
     foo(test);   // repeat the ajax call under certain conditions
  else
     alert("got it");
}


$(function() {
  foo(test);
});

This will repeat the ajax request until the response matches a certain value.

You don't want to return a value from a function that's going to make an AJAX call because the AJAX Request will not have pleted before the function returns (and personally, I disagree with the answers that say you should set async to false). You want to do something like this instead:

function retFunction(val) {
  // Do something here for various values of val
  if (val == 0) {
    // Something
  } else if (val == 1) {
    // Something else
  }
}

function foo()
  var xhr=send_request( "bla", function() {
    var myResult = 0; // Something here based on return values.
    retFunction(myResult);
  });
}
发布评论

评论列表(0)

  1. 暂无评论