将AJAX json数据传递给D3
问题描述:
我想使用AJAX XMLHttpRequest将JSON数据传递给D3来构建图形。我的代码是:将AJAX 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")
});
}
})();
我得到错误:
GET http://localhost:8000/[object%20Object] 404(未找到)
我假设默认D3希望我的一些URL传递给d3.json()并且不想接受该对象。任何想法如何通过响应(对象)到D3并将其用作数据来构建grap?
答
好吧,所以我通过删除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")
是'{%url'airline_year_financial_data'%}'一个Django模板,它实际上解决了什么? – ccprog
是的这是Django的URL,但我刚刚达到了预期的结果,并会显示我对这个问题的回答,以帮助其他人为未来。感谢您查看这个。 – Hannan