我有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