【发布时间】:2017-10-12 15:51:49
【问题描述】:
我的控制器根据视图中选择的国家/地区查询数据库。我需要通过 Ajax 将国家/地区值传递给 JavaScript。 查看以选择国家: /app/views/things/index.html.erb
<ul id = "countries">
<% @countries.each do |c| %>
<li><%= link_to c.name, {controller: "things", action: "graph", :id => c.id}, remote: true -%></li>
<% end %>
</ul>
<!-- Selected country is displayed as the current params -->
<div id="current-params"></div>
路线:
/config/routes.rb
resources :things
get 'things/graph/:id' => 'things#graph'
控制器: /app/controllers/things_controller.rb
def graph
@country = Country.find(params[:id])
respond_to do |format|
format.js
end
end
Controller 将数据发送到 js.erb: /app/views/things/graph.js.erb
$("#current-params").html("<%= j render(partial: 'graph') %>");
graph.js.erb 呈现部分: /app/views/things/_graph.html.erb
<%= "Current params: #{@country.name}" %>
当前参数:喀麦隆
我选择了喀麦隆,它在视图中显示为#current-params 的输出。这意味着循环(视图 => 控制器 => js.erb => 部分 => 视图)有效。
现在我需要通过添加 $ajax({}) 将数据从控制器发送到 JavaScript:
/app/views/things/graph.js.erb
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'things/graph/20', #I would like to generalize this to display the selected country, not just the country with ID 20. How do I specify an equivalent of params[:id] in js language?
dataType: 'js',
success: function (data) {
alert("success");
#then do something more like pass the data to D3 plot function
},
error: function (result) {
alert("error");
}
});
当我选择一个国家时返回视图,我收到一个弹出消息“错误”,表明 Ajax 调用不成功。如何成功获取 JS 中的数据?
控制台输出给出 200 OK 响应:
Started GET "/things/graph/20" for 10.240.0.225 at 2017-05-13 11:11:39 +0000
Cannot render console from 10.240.0.225! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by ThingsController#graph as */*
Parameters: {"id"=>"20", "thing"=>{}}
Country Load (0.6ms) SELECT "countries".* FROM "countries" WHERE "countries"."id" = $1 LIMIT $2 [["id", 20], ["LIMIT", 1]]
Rendering things/graph.js.erb
Rendered things/_graph.html.erb (0.3ms)
Rendered things/graph.js.erb (69.7ms)
Completed 200 OK in 74ms (Views: 71.7ms | ActiveRecord: 0.6ms)
【问题讨论】:
-
要拥有你的国家而不是 id,你应该检查 gem
friendly_id -
@jaeger 将查看
friendly_idgem
标签: ruby-on-rails