【问题标题】:Get JSON data out of the Scope从 Scope 中获取 JSON 数据
【发布时间】:2021-07-03 07:39:00
【问题描述】:

我在 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); 将函数返回给我。 console.log(getMinMax()); 返回我 undefined 并说 回调不是函数

【问题讨论】:

    标签: jquery json function callback


    【解决方案1】:

    您使用的第二种模式是有效的,并且会起作用。问题是因为在您对getMinMax() 的调用中,您需要提供回调函数作为参数。这就是您当前看到“回调不是函数”错误的原因。试试这个:

    function getMinMax(callback) {
      $.getJSON("../../dados/opcoesMinMax.json", callback);
    }
    
    getMinMax(data => {
      // this is the callback function. Work with the data here...
      console.log(data);
    });
    

    【讨论】:

    • 工作得很好。欣赏!
    猜你喜欢
    • 1970-01-01
    • 2016-02-06
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多