Har*_*esh 14 javascript jquery json
function test(){
$.getJSON( "notebook-json-data.php", function( data ) {
var myData = data;
});
}
Run Code Online (Sandbox Code Playgroud)
在我的函数中我得到了json对象,但我想myData从其函数范围的外侧访问变量.
我试过设置var myData外功能,但没有运气.. :(
我不熟悉JSON,我需要解析吗?
如何将此变量设置为全局?
请帮忙...
And*_*ndy 12
不要尝试设置myData为全局变量 - 它不起作用,因为它getJSON是异步的.要么使用承诺:
function test() {
return $.getJSON('notebook-json-data.php');
}
$.when(test()).then(function (data) {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
或者回调:
function test(callback) {
$.getJSON('notebook-json-data.php', function (data) {
callback(data);
});
}
test(function (data) {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
编辑
由于您希望在代码的其他区域中使用数据,因此请使用闭包创建一个环境,使您的变量不会泄漏到全局空间中.例如,使用回调:
(function () {
var myData;
function test(callback) {
$.getJSON('notebook-json-data.php', function (data) {
callback(data);
});
}
test(function (data) {
myData = data;
autoPopulate('field', 'id');
});
function autoPopulate(field, id) {
console.log(myData);
}
});
Run Code Online (Sandbox Code Playgroud)
myData被缓存为特定于该闭包的全局变量.请注意,其他函数只有在回调完成后才能使用该变量.
与其创建全局变量,不如调用“ done”回调,如下所示:
$.getJSON( "example.json", function(data) {
console.log( "json loaded" );
foo(data);
})
.done(function() {
console.log("");
foo1(data);
});
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参见getJSON API。
问题在于getJSON是异步的,因此在getJSON处理数据时,代码将继续执行。
function test(a){
$.getJSON( "notebook-json-data.php", function( data ) {
a = data;
}
}
var main = function() {
var a;
test(a); /* asynchronous */
console.log(a); /* here, json could be hasn't already finish, most likely, so print 'undefined'
}
Run Code Online (Sandbox Code Playgroud)