gpt4 book ai didi

javascript - 将 AJAX json 数据传递给 D3

转载 作者:行者123 更新时间:2023-11-30 21:18:49 26 4
gpt4 key购买 nike

我正在尝试使用 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() 并且不想接受该对象。知道如何将 response (object) 传递给 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")

关于javascript - 将 AJAX json 数据传递给 D3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45393480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com