D3从django序列化模型json中获取,返回空白数组



我只在真正绝望的时候写问题,我希望有人能给我指明正确的方向。

  1. 我正在尝试使用用户页面中出现的django模型中的数据来构建饼图,因此每个用户在其http get查询中都会返回不同的数据
  2. 我目前正在开发中,所以我仍在从localhost获取
  3. 我相信我的Django很好,因为js-ajax工作得很好。也许问题出在生产环境上(从本地主机获取?(

// 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一样工作。也许问题就在这里,但我不知道如何继续。

欢迎任何帮助。我真的快疯了。干杯

好的,发现了我的问题,尽管我必须使用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();

最新更新