0

My function is very simple, and based on what I found here. Yet I cant seem to make it work, whats wrong?

function ajax(url) {
    var result;
    $.ajax({
        url: url,
        success: function(data) {
            result = data;
            //$('#test').html(data);
            }
        });
    return result;
    }

The function is getting the data, for if I uncomment the commented code and call it, then the data is shown inside the #test element. However, if I write

var test = ajax('my-url.php');
$('#test').html(test);

then it doesnt work. My guess is that for some reason, the data in "data" is not being stored in the variable "result". But I cant figure out why, nor how to solve it. Any help is appreciated.

4

2 回答 2

2

The result variable is not being changed until the AJAX call finishes, by which point the ajax function has already returned. This is the entire point of callbacks, the ability to schedule a task to be executed when an event is finished.

Javascript (in-browser) is inherently asynchronous.

Alternatively, you can pass in async: false to your $.ajax call and it will wait until it's finished, but reverting back to your original style makes more sense.

Edit: It looks like what you're doing can be accomplished with $.load().

于 2012-07-19T00:52:51.850 回答
1

If you modify your $.ajax call to not execute asynchronously it will work as you expect:

function ajax(url) {
  var result;
  $.ajax({
    async: false,
    url: url,
    success: function(data) {
        result = data;
        //$('#test').html(data);
        }
    });
  return result;
}

The $.ajax function returns immediately and does not wait for the AJAX call to return.

于 2012-07-19T00:52:48.690 回答