通过Rails中的Ajax将数据从控制器传递到javascript

时间:2017-05-13 11:45:43

标签: ruby-on-rails

我的控制器根据视图中选择的国家/地区查询数据库。我需要通过Ajax将country值传递给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}" %>

目前的参数:喀麦隆
我选择了Cameroon,它在视图中显示为#current-params的输出。意味着循环(view =&gt; controller =&gt; js.erb =&gt; partial =&gt; view)有效。 现在我需要通过添加$ 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");
   }
});

当我选择一个国家/地区时,回到视图中,我会弹出一条消息&#34;错误&#34;表明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)

1 个答案:

答案 0 :(得分:0)

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

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

然后,您可以使用与在JavaScript中写入对象相同的方式访问对象。

除此之外,您可以随时在HTML中使用Rails变量,而不需要任何额外的宝石:

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

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