This question already has an answer here:
这个问题在这里已有答案:
- How do I return the response from an asynchronous call? 31 answers
如何从异步调用返回响应? 31个答案
Hello i am getting undefined when reading a json file using ajax file. It returns undefined:
您好我在使用ajax文件读取json文件时未定义。它返回undefined:
var input;
$.getJSON('cake.json', function(data) {
input = data;
});
console.log('Result'+input);
but the variable input returns undefined.
但变量输入返回undefined。
1 个解决方案
#1
0
You have this:
你有这个:
var input = [];
$.getJSON('cake.json', function(data) {
input = data;
});
// This will likely execute BEFORE getJSON has returned 'data'
console.log('Result' + input);
But try this and, assuming you're actually getting data, you should see results in the console.
但试试这个,假设你实际上正在获取数据,你应该在控制台中看到结果。
var input = [];
$.getJSON('cake.json', function(data) {
input = data;
console.log('Result' + input);
});
(Another way to debug to make sure your JSON call is working is to use the network debugger.)
(调试以确保您的JSON调用正常工作的另一种方法是使用网络调试器。)
If you don't need input
to be in the global scope (see here about scope of variables in JavaScript), you can just do this:
如果您不需要输入在全局范围内(请参阅此处有关JavaScript中变量的范围),您可以这样做:
$.getJSON('cake.json', function(data) {
// do something with the 'data'
});
or:
$.getJSON('cake.json', function(data) {
process(data);
});
function process(data) {
// do something with data
}
#1
0
You have this:
你有这个:
var input = [];
$.getJSON('cake.json', function(data) {
input = data;
});
// This will likely execute BEFORE getJSON has returned 'data'
console.log('Result' + input);
But try this and, assuming you're actually getting data, you should see results in the console.
但试试这个,假设你实际上正在获取数据,你应该在控制台中看到结果。
var input = [];
$.getJSON('cake.json', function(data) {
input = data;
console.log('Result' + input);
});
(Another way to debug to make sure your JSON call is working is to use the network debugger.)
(调试以确保您的JSON调用正常工作的另一种方法是使用网络调试器。)
If you don't need input
to be in the global scope (see here about scope of variables in JavaScript), you can just do this:
如果您不需要输入在全局范围内(请参阅此处有关JavaScript中变量的范围),您可以这样做:
$.getJSON('cake.json', function(data) {
// do something with the 'data'
});
or:
$.getJSON('cake.json', function(data) {
process(data);
});
function process(data) {
// do something with data
}