How to create d3 graph using data from Rails database

。_饼干妹妹 提交于 2020-01-01 07:06:13

问题


I learned to create d3 graph using the d3 book, in which all the dataset is included directly in the <script> tag, which is in turn included in the html body.

I now want to use d3 in my rails app, but I don't know how to:

  1. Pass data from my Rails database to my d3 script
  2. How to "partial out" the javascript? I have seen materials on "unobstrusive javascript", but they are usually about AJAX form submission and I have a hard time converting that to graph drawing (i.e. including a <div> with graph drawn using app data).

There is still not an answer that deals with both of these issues yet, so hopefully this becomes a reference for future Googlers.


回答1:


In my opinion requesting the data via AJAX would be the "cleanest" way to do that. You could use jQuery's ajax method to do a GET request to say '/get_data.json' ( which you have to add to your routes.rb), which would return you a JSON with the data.

Something like this.

//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
}

(Note that this JS code is a remake of the answer here)

This is how your controller providing the data could look like(note I made a new controller, you might not want to do that and just use a new action in an existing controller):

#app/controllers/data_controller.rb
class DataController < ApplicationController
  def get_data
    respond_to do |format|
      format.json {}
    end
  end
end

And this is how your data could look like:

#app/views/data/get_data.json
[1,1,2,3,5,8,13,21,34,55]


来源:https://stackoverflow.com/questions/24494632/how-to-create-d3-graph-using-data-from-rails-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!