简体   繁体   English

在D3中使用JSON数据

[英]Using json data in d3

I want to use the json data later in my code so have put it into a variable and return the variable to a function. 我想稍后在代码中使用json数据,因此将其放入变量中并将变量返回给函数。 If I hard code the json data it works (see below, the second part of the code is only so that I can check that it works) 如果我对json数据进行了硬编码(请参见下文,那么代码的第二部分只是为了让我可以检查其是否有效)

function read() {
var data = [{"APSYear":"2014","Domain":"Reading","Level":"3","KWC":"469.62","Aus":"418.3","Vic":"431.7","P90":"544.92"}];
data.forEach(function(d) {
     readkwc = d.KWC;
     readvic = d.Vic;
     read90 = d.P90;    
});
return [readkwc, readvic, read90];
}
var read = read();
var body = d3.select('body');
body.append('p')
    .text(read[0])
    .append('p')
    .text(read[1])
    .append('p')
    .text(read[2]);

but if I read the json code from a file it doesn't work (see below) 但是如果我从文件中读取json代码,它将无法正常工作(请参见下文)

function read() {
d3.json("statsread.php", function(error, data) {
data.forEach(function(d) {
    readkwc = d.KWC;
    readvic = d.Vic;
    read90 = d.P90; 
    });
}); 
return [readkwc, readvic, read90];
}
var read = read();
var body = d3.select('body');
    body.append('p')
        .text(read[0])
        .append('p')
        .text(read[1])
        .append('p')
        .text(read[2]);

Where am I going wrong? 我要去哪里错了?

  • You are making an asynchronous request to "statsread.php" inside a function, hence you will get the data immediately. 您正在函数内部向“ statsread.php”发出异步请求,因此您将立即获取数据。 Hence var read = read(); 因此var read = read(); will be undefined. 将是不确定的。

  • The variables "readkwc, readvic, read90" will be unavailable when the API is failed, so you need to handle the failure case as well. 当API失败时,变量“ readkwc,readvic,read90”将不可用,因此您也需要处理失败情况。

Here is the fix. 解决方法是这里。

 var body = d3.select('body'); function read() { d3.json("statsread.php", function(error, data) { if (error) return console.warn(error); data.forEach(function(d) { readkwc = d.KWC; readvic = d.Vic; read90 = d.P90; }); var read = [readkwc, readvic, read90]; body.append('p') .text(read[0]) .append('p') .text(read[1]) .append('p') .text(read[2]); }); } read(); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM