问题
Update: My question was answered, but I wrote a blog post detailing exactly how I went about doing this: http://lathamcity.com/posts/ajaxInRails.html
I have a page that shows a list of things based on a Ruby object. My goal is to make an Ajax call to get a new Ruby object and then update the list based on that.
I thought that the way to do this was with partials. I make the entire list a partial file with the Rails instance variable in the code. Then I want the Ajax call to set the corresponding instance variable to the new list and re-render the partial.
That's the end goal, but right now I'm trying to do a really basic version of that where I just set an instance variable to a string and then show the string.
So in my div, I have:
<% form_tag :action => :go , :method => :get, :remote => true do %>
<%= submit_tag "Go" %>
<% end %>
<div id="test"><%= render(:partial => 'test') %></div>
There's a _test.erb file in the views/interface
(the name of my controller) folder, with only the following line as its contents:
<%= @test %>
And then in my controller,
def go
@test = "Hello You"
render :update do |page|
page.replace_html "test", :partial => "test"
end
end
When I run this, I get: Missing template interface/update, application/update
I don't know much about render :update
, I found it in an example on Google.
What am I doing wrong that is causing this problem and how can I fix it? Am I going about this the right way or is there a better way to do it?
回答1:
I think both render :update
and replace_html
were deprecated/removed in rails 3.1. The standard way of doing partial updates is to use a js.erb template.
In your controller, tell your action to respond to js request:
@test = "Hello you"
respond_to do |format|
format.js
end
Create the js response template app/views/interface/go.js.erb:
$('#test').html("<%= escape_javascript(render('test', test: @test})) %>")
and change the partial code to <%= test %>
because this is no longer an instance variable; rather, test is being passed to the partial as an argument from the js.erb template with test: @test
来源:https://stackoverflow.com/questions/12554296/dynamically-update-page-based-on-an-instance-variable-from-ajax