在我看来,通过 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的翻版)
这就是你的控制器提供数据的样子(注意我创建了一个新控制器,你可能不想这样做,而只是在现有控制器中使用一个新动作):
#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]