我有rails 3.1,当我使用ajax进行删除操作时,页面没有显示更新的内容而没有手动刷新。在使用rails的ajax调用后,页面不显示更新的信息
奇怪的是,所有.js.erb代码似乎正在正确触发。我甚至尝试在destroy.js.erb中放入一个简单的page.alert('hi'),但删除后我没有收到任何警报。我看到一些地方提到在视图中为ajax添加一个“脚本”标记以使jquery工作,但最新的教程没有提到这一点。我会感谢你的帮助。
这是我看到在服务器日志:
Started DELETE "/categories/35" for 127.0.0.1 at 2011-12-19 12:58:15 -0500
Processing by CategoriesController#destroy as JS
Parameters: {"id"=>"35"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 5 LIMIT 1
Category Load (0.3ms) SELECT "categories".* FROM "categories" WHERE "categories"."user_id" = 5 AND "categories"."id" = ? LIMIT 1 [["id", "35"]]
SQL (0.5ms) DELETE FROM "categories" WHERE "categories"."id" = ? [["id", 35]]
Rendered categories/destroy.js.erb (0.5ms)
Completed 200 OK in 161ms (Views: 30.7ms | ActiveRecord: 3.2ms)
以下是我在生成的HTML页面输出页面的源代码,请参阅:
...
<tr id = "category_35">
<td>High-end products</td>
<td class="deletebutton"><a href="/categories/35" data-confirm="Are you sure?" data-method="delete" data-remote="true" rel="nofollow">Delete</a></td>
</tr>
<tr id = "category_36">
<td>Economy products</td>
<td class="deletebutton"><a href="/categories/36" data-confirm="Are you sure?" data-method="delete" data-remote="true" rel="nofollow">Delete</a></td>
</tr>
destroy.js.erb的内容:
('#<%= dom_id(@category) %>').fadeOut(700);
在Gemfile中:
gem 'jquery-rails'
在categories_controller.rb:
def index
@categories = current_user.categories.all
respond_to do |format|
format.html # index.html.erb
format.json
format.js
end
end
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url }
format.js {
render :template => 'categories/destroy.js.erb', :layout => false
}
end
end
在应用程序/视图/类别/ index.html.erb
<h2>Categories</h2>
<table name="categories_list">
<%= render "categories_list" %>
</table>
<br />
在部分_categories_list.html.erb
<% @categories.each do |category| %>
<tr id = "<%= dom_id(category)%>">
<td><%= category.name %></td>
<td class="deletebutton"><%= link_to 'Delete', category, confirm: 'Are you sure?', method: :delete, :remote => true %></td>
</tr>
<% end %>
你的ajax调用看起来像 – Rafay 2011-12-19 18:15:20
我没有放任何单独的ajax调用代码。我正在使用不显眼的方法。正如你所看到的,我把:remote => true放在删除按钮上。这有帮助吗? – Tabrez 2011-12-19 19:16:59
@ 3nigma,我是否需要在application.js中添加任何设置代码?我看到一些老的教程提到ajax设置,但是我们需要使用最新的rails 3.1吗? – Tabrez 2011-12-19 19:38:21