d3.JS JSON数据导入 - 不在全局范围内 [英] d3.JS JSON data import - not in global scope

查看:146
本文介绍了d3.JS JSON数据导入 - 不在全局范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json:

{
    "temp_data": [10,15,20]
}

我要尝试导入:

var temp_data;
//Importing from JSON
if(true){
    d3.json("graph.json", function(error, graph) {
        if (error){
            throw error;
        }
        temp_data = graph.temp_data;
        console.log(temp_data);    //works
    });
}

console.log("temp: " + temp_data); //Does not work

问题是,尽管将temp_data声明为全局变量,数据。

Problem is, despite declaring temp_data as global variable, the second log is not showing data.

推荐答案

传入 d3.json()的回调异步: https://github.com/d3/d3/wiki/Requests#d3_json

这意味着您的第二个console.log()实际上在graph.json检索之前运行,因此在您的全局变量填充。您需要在回调中使用此数据进行处理。

This means your second console.log() actually runs before "graph.json" has been retrieved, and therefore before your global variable is populated. You need to do your work with this data inside the callback instead.

这篇关于d3.JS JSON数据导入 - 不在全局范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆