我尝试使用AJAX XMLHttpRequest将JSON数据传递给D3来构建图表。我的代码是:
<script>
(function() {
var url = "{% url 'airline_year_financial_data' %}";
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url)
httpRequest.send()
}
// Handle XHR Response
function responseMethod () {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
updateUISuccess(httpRequest.responseText)
} else {
// Do something
}
}
}
// Handle XHR Success
function updateUISuccess(responseText) {
var response = JSON.parse(responseText)
console.log(response) // Correctly logs json data in console.
console.log(typeof(response)) // Shows the type is 'object' in console.
// Build D3 Chart
d3.json(response, function (data) {
var width = 500;
var height = 300;
var padding = 20;
d3.select("body")
.append("svg")
.attr("class", "waterfall-container")
.attr("width", width)
.attr("height", height)
.attr("style", "outline: thin solid")
d3.select("svg")
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x-axis", 200)
.attr("y-axis", 300)
.attr("width", 20)
.attr("height", 200)
.attr("fill", "blue")
});
}
})();
我收到错误:
获取http://localhost:8000/[object%20Object] 404(未找到)
我假设默认情况下D3要我将一些URL传递给d3.json()并且不想接受该对象。我知道如何将 响应(对象) 传递给D3并将其用作构建grap的数据?
答案 0 :(得分:1)
好的,所以我通过删除d3.json调用实现了预期的结果,因为我不必使用d3将JSON数据再次转换为JSON。现在数据直接流向d3代码。
var width = 500;
var height = 300;
var padding = 20;
d3.select("body")
.append("svg")
.attr("class", "waterfall-container")
.attr("width", width)
.attr("height", height)
.attr("style", "outline: thin solid")
d3.select("svg")
.selectAll("rect")
.data(response) // Here I'm passing AJAX Data
.enter()
.append("rect")
.attr("x-axis", 200)
.attr("y-axis", 300)
.attr("width", 20)
.attr("height", 200)
.attr("fill", "blue")