我只在真正绝望时才写问题,希望有人能指出正确的方向。
// javascript
var original_data = [{
"coin": "BTC",
"stake": 5
},
{
"coin": "LTC",
"stake": 6
},
{
"coin": "DASH",
"stake": 9
}
];
var data = [];
var url = "http://localhost:8000/wallet/data";
d3.json(url, (datos) => {
loadGraph(datos)
});
function loadGraph(data) {
console.log("NEW DATA: ");
console.log(data);
var svgWidth = 500,
svgHeight = 300,
radius = Math.min(svgWidth, svgHeight) / 2;
var svg = d3.select('svg')
.attr("width", svgWidth)
.attr("height", svgHeight);
//Create group element to hold pie chart
var g = svg.append("g")
.attr("transform", "translate(" + svgWidth / 2 + "," + radius + ")");
var color = d3.scaleOrdinal(d3.schemeCategory10);
var pie = d3.pie().value(function(d) {
return d.stake;
});
var path = d3.arc()
.outerRadius(radius)
.innerRadius(radius / 2);
var arc = g.selectAll("arc")
.data(pie(data))
.enter()
.append("g");
arc.append("path")
.attr("d", path)
.attr("fill", function(d) {
return color(d.data.stake);
});
var label = d3.arc()
.outerRadius(radius)
.innerRadius(0);
arc.append("text")
.attr("transform", function(d) {
return "translate(" + label.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.data.coin + ":" + d.data.stake + "%";
});
}
// TRYING WITH D3js json method:
d3.json(url).then((data) => {
console.log(data);
console.log(url);
});
// ** Data returns empty array!
// ** Maybe need to do something first?
// TRYING WITH js ajax method:
// var xhttp = new XMLHttpRequest();
// xhttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// var data = this.responseText;
// console.log(this.responseText);
// loadGraph(data);
// }
// };
// xhttp.open("GET", url, true);
// xhttp.send();
// ** Data loads fine, but d3 will not paint chart.
// ** Instead, undefined is printed where the graph should be.
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.js"></script>
如代码中所示,我已加载示例数据以确保饼图定义正确。它可以处理示例数据,但可能需要进行一些更改才能使其从外部资源运行。
我在网络上看到的有关外部数据源的示例通常指向存储在某处的.json文件。这没有意义,因为它像API一样工作。也许问题出在这里,但我不知道如何继续。
欢迎任何帮助。我真的很生气。 干杯。
答案 0 :(得分:0)
好吧,尽管我不得不使用javascript ajax查询,但发现了我的问题。 我认为通过ajax查询恢复的数据格式不正确是正确的。 我做到了:
var data = JSON.parse(this.response); //Instead of this.responseText
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.response);
loadGraph(data);
}
};
xhttp.open("GET", url, true);
xhttp.send();