-3

我在使用 $.get 函数之外的变量时遇到问题,找不到该变量并且脚本停止。

我能做些什么?

$.get("../ajax.php", function (data) {
    var json = JSON.parse(data);
    test = json['jquery']['test'];
});

alert(test)

更新:(这解决了我的问题)我用 $.get 得到了 json。并将其传递给我的函数,json 将能够稍后在脚本中获取。

$.get("../ajax.php", function (data) {
function(data) {                    
    loadApp(data);
});

function loadApp(data) {    
    json = JSON.parse(data);                
}
4

1 回答 1

0

Since it's a asynchronous call, all processing will have to be made in the callback function. Put your alert(test) inside the callback function instead.

EDIT:

$.get("../ajax.php", function (data) {
    var json = JSON.parse(data);
    test = json['jquery']['test'];

    alert(test); // Needs to be processed in this scope
});

This occurs since the JavaScript processor reads line by line, detects the ajax-call and sends it, it then jumps to the alert, which will try to alert a non-existing variable. Even if you declare it gobally it wont work; since the AJAX-return is asynchronous, and will therefore be executed in parallel to the other code.

于 2013-11-06T09:54:39.043 回答