当前位置: 动力学知识库 > 问答 > 编程问答 >

Why cant I get the result out of the jQuery AJAX

问题描述:

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.

网友答案:

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().

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: