我学会了使用 d3 book 创建 d3 图,其中所有数据集都直接包含在 <script>
中标签,它又包含在 html
中 body 。
我现在想在我的 Rails 应用程序中使用 d3,但我不知道如何:
- 将数据从我的 Rails 数据库传递到我的 d3 脚本
- 如何“分出”javascript?我看过关于“不显眼的 javascript”的 Material ,但它们通常是关于 AJAX 表单提交的,我很难将其转换为图形绘制(即包括一个
<div>
以及使用应用程序数据绘制的图形)。
目前还没有解决这两个问题的答案,因此希望这能成为 future Google 员工的引用。
最佳答案
在我看来,通过 AJAX 请求数据是“最干净”的方式。您可以使用 jQuery 的 ajax 方法来执行 GET 请求以说“/get_data.json”(您必须将其添加到您的 routes.rb
),这将返回一个包含数据的 JSON。
像这样。
//your JS file
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '/get_data',
dataType: 'json',
data: "{}",
success: function (received_data) {
var div_where_to_draw = "div.mygraph";
your_d3_function(div_where_to_draw, received_data);
},
error: function (result) {
}
});
function draw_histogram(where_to_draw, data_to_draw){
//Your d3js code here
}
(请注意,此 JS 代码是对答案 here 的翻版)
这就是你的 Controller 提供数据的样子(注意我做了一个新的 Controller ,你可能不想这样做而只是在现有的 Controller 中使用一个新的 Action ):
#app/controllers/data_controller.rb
class DataController < ApplicationController
def get_data
respond_to do |format|
format.json {}
end
end
end
这就是您的数据的样子:
#app/views/data/get_data.json
[1,1,2,3,5,8,13,21,34,55]
关于javascript - 如何使用 Rails 数据库中的数据创建 d3 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24494632/