json - 如何存储从文件加载的JSON对象?

标签 json d3.js

我想将加载的JSON对象存储在变量中。
通常我应该做类似的事情:

d3.json("jsondatafile.json", function(json){ DO SOMETHING; });

但是,相反,我想要这样的东西:
var jsonData = d3.json("jsondatafile.json");

我想在jsonData函数之外访问d3.json。我怎样才能做到这一点?

最佳答案

您可以始终同步使用jQuery.ajax():

var jsonData;
$.ajax({
  dataType: "json",
  url: "jsondatafile.json",
  async: false
  success: function(data){jsonData = data}
});

但是,不建议按照jQuery API中的说明进行操作:

The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.



函数 d3.json() 是异步的。因此,在读取data变量之前,您必须等待数据被接收。这就是为什么在处理异步数据时,实践是在d3.json()函数内做所有事情的原因:
d3.json("temp.json", function(data){
    //use data here
})
// do not use data anymore

注意:答案来自我之前的答案:How to import json data in D3?

关于json - 如何存储从文件加载的JSON对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16455194/

相关文章:

python - 在 Apache Spark 中读取 pretty-print json 文件

json - 在ListView中显示嵌套的json数组

javascript - 保护客户端 Web 服务的策略

javascript - d3.js 更新带按钮的条形图工具提示

javascript - D3.js、csv 和 foreach 未定义值

d3.js - 在 D3 多线图上创建点

javascript - D3 将数据添加到 3D 饼图

php json_encode mysql 结果以特定方式

javascript - 使用 C3.js 加载区域

c# - Web Api 模型绑定(bind)和多态继承