【问题标题】:Pass data from controller to javascript via Ajax in Rails通过 Rails 中的 Ajax 将数据从控制器传递到 javascript
【发布时间】: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_id gem

标签: ruby-on-rails


【解决方案1】:

在我看来,将数据从 Ruby on Rails 传递到 JavaScript 最简单的解决方案是 Gon。它基本上允许将数据写入控制器中的gon-object 并在视图中访问它:

# your_controller.rb
def index
  gon.your_variable = "Foobar"
end

然后,您可以像在 JavaScript 中写入对象一样访问该对象。

除此之外,您始终可以像这样在 HTML 中使用 Rails 变量,而无需任何额外的 gem:

<%= javascript_tag do %>
  window.your_variable = '<%= j @your_rails_variable %>';
<% end %>

然后您可以通过 JavaScript 中的 window-object 访问所有内容。

【讨论】:

  • 我将探索 gon,看看它如何解决问题
猜你喜欢
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
相关资源
最近更新 更多