【问题标题】:filled array is empty outside function填充数组在函数外为空
【发布时间】:2014-11-20 05:53:43
【问题描述】:

我尝试从 ajax json 推入我的数组循环数据,但 $.getJSON("/admin/reports/stats/1", function(datas) {}); 之外的数据变量为空

var data = [];
$.getJSON("/admin/reports/stats/1", function(datas) {
    $(datas).each(function(index, value){
        obj={};
        obj['label']= value.publisher_name;
        obj['data']=  value.sale;
        data.push(obj);
    });
    console.log(data); //here I see the content of array    
});

console.log(data); //here is empty

【问题讨论】:

  • 你会找到答案和解释here
  • 使用 .done() 并在那里对您的数据执行操作。

标签: jquery arrays variables each


【解决方案1】:

getJSON 是异步的,所以:

console.log(data); //here is empty  

在可以下载 JSON 之前实际执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多