开发者

jQuery: a function containing an ajax() function won't return ajax() response

In an attempt to make my jQuery code modular, i.e. reusable, I've placed an ajax() function inside of another function fetch_ajax(). I'm trying to call fetch_ajax() with parameters from other places, which should simply run the contained ajax() and return the response.

But that's not happening - instead, fetch_ajax() apparently returns false too quickly to the caller and doesn't wait until ajax() has completed the request and gotten a response.

Here's the code:

The fetch_ajax() function

function fetch_ajax(url) {
  $.ajax({
    type: 'GET', 
    url: url,
    success: function(response) {
      return response;
    }
  });
}

The calling function:

function caller() {
  response = fetch_ajax('script.php');
  alert(response); /开发者_JAVA百科/this is always 'undefined'
}

In fetch_ajax(), I've tried not directly returning response from within ajax(), but writing it to a variable, and returning that variable after ajax() - that didn't work either (same result).

When I place a 2nd alert right before return response; inside of the ajax() function, I'm seeing that one fire AFTER the one inside caller(). So I'm thinking that somehow, fetch_ajax() doesn't wait for the contained function to execute before it returns false.

What am I doing wrong?

Thank you.


Your train of thought is wrong - the .ajax() function is written to not wait for the contained function. success is an event listener, so it is fired dynamically whenever the response arrives. You could use synchronous requests or jQuery queues to solve this, but both have disadvantages.

See How do I make jQuery wait for an Ajax call to finish before it returns? for the synchronous request solution. It's much simpler than the other one, but will hang your browser if the server dies right then or a hyperactive firewall blocks the answer or an angry lolcat eats your request on the way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜