从范围中获取 JSON 数据
Get JSON data out of the Scope
我在 JSON:
中有这些数据
{"minmax":["0.01","67.00"]}
我想使用 jQuery 获取它,这就是我正在做的:
$.getJSON("../../dados/opcoesMinMax.json", function(data) {
var getMinMax = data;
});
// Need to use data here, out of the scope
我也尝试过使用回调来做到这一点,这样做:
function getMinMax(callback) {
$.getJSON("../../dados/opcoesMinMax.json", function(data) {
callback(JSON.stringify(data));
});
}
// Need to use data here, out of the scope
即使使用回调,我也无法恢复数据。 console.log(getMinMax);
returns 我的功能。
console.log(getMinMax());
returns 我未定义并说 回调不是函数.
您使用的第二个模式有效,并且会起作用。问题是因为在调用 getMinMax()
时,您需要提供回调函数作为参数。这就是您当前看到 'callback is not a function' 错误的原因。试试这个:
function getMinMax(callback) {
$.getJSON("../../dados/opcoesMinMax.json", callback);
}
getMinMax(data => {
// this is the callback function. Work with the data here...
console.log(data);
});
我在 JSON:
中有这些数据{"minmax":["0.01","67.00"]}
我想使用 jQuery 获取它,这就是我正在做的:
$.getJSON("../../dados/opcoesMinMax.json", function(data) {
var getMinMax = data;
});
// Need to use data here, out of the scope
我也尝试过使用回调来做到这一点,这样做:
function getMinMax(callback) {
$.getJSON("../../dados/opcoesMinMax.json", function(data) {
callback(JSON.stringify(data));
});
}
// Need to use data here, out of the scope
即使使用回调,我也无法恢复数据。 console.log(getMinMax);
returns 我的功能。
console.log(getMinMax());
returns 我未定义并说 回调不是函数.
您使用的第二个模式有效,并且会起作用。问题是因为在调用 getMinMax()
时,您需要提供回调函数作为参数。这就是您当前看到 'callback is not a function' 错误的原因。试试这个:
function getMinMax(callback) {
$.getJSON("../../dados/opcoesMinMax.json", callback);
}
getMinMax(data => {
// this is the callback function. Work with the data here...
console.log(data);
});