我使用Rails的标准ajax库。我知道事件正在发生,因为如果我刷新页面,元素更新得很好。下面是我初始化ajax的视图代码。
<% form_tag('switch_car', :method => :put, :remote => true) do %>
<div class="field">
<label>Car Name:</label>
<%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"))%><%= submit_tag "Switch Car" %>
</div>
<% end %>
这里是我的update.js.rjs
page.replace_html('entries', render(@miles))
这是视图中应该更新的部分。
<div id="entries">
<%= render(@miles)%>
</div>
这是我的控制器代码。
def update
respond_to do |format|
if params[:id]
session[:car_info_id] = params[:id]
format.html {redirect_to entry_url}
format.js
else
redirect_to switch_car_path
end
end
end
我不知道为什么它不修改DOM,所以更新显示没有刷新页面?我可以在服务器控制台中看到它运行javascript,但视图没有更新。
控制台输出:
Started POST "/switch_car" for 127.0.0.1 at 2011-08-03 17:32:02 -0400
Processing by ActiveCarController#update as JS
Parameters: {"utf8"=>"Γ£ô", "authenticity_token"=>"PEbdqAoiik37lcoP4+v+dakpYxdpMkSm7Ub8eZpdF9I=", "id"=>"10", "commit"=>"Switch Car", "_"
=>""}
Rendered active_car/update.html.erb (0.0ms)
Completed 200 OK in 16ms (Views: 16.0ms | ActiveRecord: 0.0ms)
问题一直是我在错误的目录下有我的update.js.rjs。您需要将它放在操作发生的视图目录中,而不是提供数据的视图目录中。最后让我明白的是update.js.rjs从来没有被渲染(见上面的终端输出)。它说重新命名update.html.erb,因为它找不到update.js.rjs。如果其他人有这个问题请确保你的update。js。rjs正在被渲染。