-2

我有这样的事情:

$.ajax({
    type: 'GET',
    url: my_url,
    success: function(data) {

        $('#some_div').data('test', 'This is a test');

    }
});

然后在成功回调之外,我尝试访问我的测试变量,例如

console.debug($('#some_div').data('test'));

但这会返回undefined

请提供任何帮助

谢谢

4

3 回答 3

0

You need to familiar yourself with the $.ajax .done() and .fail() methods.

jqXHR.done(function(data, textStatus, jqXHR) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function(jqXHR, textStatus, errorThrown) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

More Info Here!

于 2013-08-26T16:49:40.273 回答
0

The success function happens AFTER the request returns successfully.

Your console.debug line happens immediately after you make the $.ajax call, i.e. before the value it's inspecting gets set by the ajax success callback:

  1. $('#some_div').data('test') is undefined
  2. ajax call is made
  3. $('#some_div').data('test') is still undefined!
  4. Your console.debug line runs
  5. $('#some_div').data('test') is still undefined...
  6. Your ajax call returns sucessfully; $('#some_div').data('test') gets defined now

Yes, this is the most simple example of how asynchronous logic works, hence the comments you're getting.

于 2013-08-26T16:49:47.573 回答
0

You'll need to store the result in a global variable, i.e:

var globalVariable;
$.ajax({
    type: 'GET',
    url: my_url,
    success: function(data) {

        $('#some_div').data('test', 'This is a test');
        globalVariable = data;
    }
});

Storing things in the global scope isn't the best idea, so I'd recommend wrapping it in a Self-Executing Anonymous Function to avoid poluting the global scope.

(Note: there are better ways of doing it, but avoiding complicating it too much)

于 2013-08-26T16:50:07.747 回答