如何从ajax访问实例变量?

时间:2013-08-28 16:59:15

标签: jquery ruby-on-rails ajax ruby-on-rails-3

我有一个名为User的模型,并在其index.html.erb文件中有一个链接,该链接调用负责检索用户经过身份验证的雷达的ajax请求。那是:

//user.js
function retrieve_radars() {
  $.ajax({
    type: "GET",
    url:  "/radars",

    success: function(data) {
      console.log(data);
    }
  });
}

#app/controllers/radars_controllers.rb
def index
  user    = current_user;
  @radars = Radar.where(:user_id => user.id)
  @radars
end

成功ajax响应后,如何在“users / index.html.erb”中迭代@radars实例变量?我想做这样的事情:

<% unless @radars.nil? %>
  <table>
  <% @radars.each do |radar| %>
    <tr>
      <td>Name</td>
      <td><%= radar.name %></td>
    </tr>
  <% end %>
  </table>
<% end %>

有任何帮助吗? 感谢

1 个答案:

答案 0 :(得分:2)

//user.js
function retrieve_radars() {
  $.ajax({
    type: "GET",
    url:  "/radars",

    success: function(data) {
      //load the response from radar#index into the div (or any other element
      $("#my_div").html(data); 
    }
  });
}

#app/controllers/radars_controllers.rb
def index
  user    = current_user;
  @radars = Radar.where(:user_id => user.id)
  render :partial => "radars", :layout => false #render partial. 
end

#app/views/radars/_radars.html.erb create partial file
<% unless @radars.nil? %>
  <table>
  <% @radars.each do |radar| %>
    <tr>
      <td>Name</td>
      <td><%= radar.name %></td>
    </tr>
  <% end %>
  </table>
<% end %>