我正在遵循RoR入门指南,并在学习过程中添加一些内容。具体来说,我想在第 5.13 删除文章 步中使用AJAX删除文章而不是使用标准模式。
我希望以最符合RoR方式的方式实现这一点。在阅读了在Rails中使用JavaScript一章后,以下步骤似乎是可行的:
- 将
remote: true
属性添加到link_to
帮助程序(请参见代码片段A) - 通过添加
data:{turbolinks:false}
来禁用 turbolinks 这个link_to
帮助程序(请参见代码片段A) - 在控制器中添加一些逻辑,以确保返回JSON(请参见代码片段B)
- 添加监听
ajax:success
事件的 JavaScript,然后对该项目进行动画处理(请参见代码片段C)
片段 A
<td><%= link_to 'Destroy',
article_path(article),
method: :delete,
data: {turbolinks: false, remote: true},
:class=> 'remove-article' %></td>
段落标签Snippet B
def destroy
@article = Article.find(params[:id])
respond_to do |format|
if @article.destroy
format.html { redirect_to articles_path }
format.json { render json: @article }
else
format.html { render action: "index" }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
片段 C
(function(){
$(document).on('turbolinks:load', listenForArticleDelete);
function listenForArticleDelete() {
$('a.remove-article').on('ajax:success', function(e, data, status, xhr) {
// e.preventDefault();
console.log('DELETE: AJAX SUCCESS', e, '\n', data, '\n', status, '\n', xhr);
});
}
})();
这不是我预期的工作方式:
- 禁用turbolinks没有生效:它仍然替换了整个页面内容。
- 事件
ajax:success
被触发,但是当我检查该事件的数据属性时,我看到一些奇怪的东西。它似乎是Turbolinks即将要做或刚刚完成的文本表示(?!)。Turbolinks.clearCache() Turbolinks.visit("http://localhost:3000/articles", {"action":"replace"})
显然我做错了,有人能否请解释一下我应该如何做?即不仅是如何使其工作,而且还要以惯用的RoR方式实现?
#编辑 我发现了罪魁祸首是片段B,因为format.html在format.json之前运行。只需交换这两个就可以解决问题:
修订后的片段A:
<!-- Default delete -> format.html -->
<td><%= link_to 'Destroy default',
article_path(article),
method: :delete,
:class=> 'remove-article' %></td>
<!-- aSync delete -> format.json -->
<td><%= link_to 'Destroy aSync',
article_path(article),
method: :delete,
remote: true,
data: {turbolinks: false},
:class=> 'remove-article' %></td>
修改后的代码片段 B:
def destroy
@article = Article.find(params[:id])
respond_to do |format|
if @article.destroy
# Must place json before html, otherwise html will be executed
format.json { render json: @article }
format.html { redirect_to articles_path }
else
format.json { render json: @article.errors, status: :unprocessable_entity }
format.html { render action: "index" }
end
end
end
destroy.js.erb
在哪里?在\views\articles
文件夹中吗? - Hendrik:remote => true
这一部分,我会编辑答案。 - Brad