【发布时间】:2015-06-05 17:36:23
【问题描述】:
这需要我几个小时。如果有人能准确地告诉我如何做到这一点,那就太好了..
我想要做的就是将一个 JSON 对象传递给一个带有 ajax 调用的 html.erb 页面,以获取 d3.js 图形。我发现的大多数解释都使用 json 文件,而我的设置使用 JSON 对象。
我的代码如下:模型(user.rb)
class User < ActiveRecord::Base
has_many :relationships
end
class User
def self.including_relationships
User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select("users.name, relationships.user_id, relationships.followsid,users.value").each_with_object(Hash.new{|h, k| h[k] = []}) do |a, obj|
obj['nodes'] << a.slice('name')
obj['links'] << a.slice('user_id', 'followsid', 'value')
end
end
end
控制器:user_controller.rb
class UserController < ApplicationController
def index
render :json => User.including_relationships
end
def data
render :json => User.including_relationships
end
我的 routes.rb 是
Rails.application.routes.draw do
get 'user/data' => 'user#data'
resources :user
end
视图 (index.html.erb)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic HTML5 Template</title>
<link href="stylesheets/style.css" rel="stylesheet" type="text/css" media="screen" />
<script src="example.js"></script>
</head>
<body>
<script>
$.ajax({
type: 'GET',
url: 'localhost:3000/user/index',
success: function(data) {
var miserables = data
}
})
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json(miserables, function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
</script>
</script>
</body>
</html>
end
没有错误,但是我返回的只是 JSON 格式的数据。我希望视图使用来自
的 JSON 对象 render :json => User.including_relationships
虽然我把它放在 ajax 脚本中
$.ajax({
type: 'GET',
url: 'localhost:3000/user/index',
success: function(data) {
var miserables = data
}
})
应该是这样的。但事实并非如此。我似乎没有成功地将 JSON 对象传递给我不认为的 ajax。
【问题讨论】:
标签: ruby-on-rails ajax json d3.js