1
我想使用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?
是'{%url'airline_year_financial_data'%}'一個Django模板,它實際上解決了什麼? – ccprog
是的這是Django的URL,但我剛剛達到了預期的結果,並會顯示我對這個問題的回答,以幫助其他人爲未來。感謝您查看這個。 – Hannan