这个问题是我昨天问的一个问题,它涉及将模型的创建/编辑功能移动到其索引页面上。我遇到的最后一个问题是,当我去删除一个模型时,我有一些应该运行的 javascript 重新加载模型列表以反映数据库中的更改。这个 js 被渲染为 html。这是我认为相关的代码:
在我的控制器中:
def destroy
@post = Post.find(params[:id])
@post.destroy
flash[:notice] = "Successfully destroyed post."
@posts = Post.all
respond_to do |format|
format.js {render :content_type => 'text/javascript' }
end
end
我的部分帖子列表(其中包含我所指的销毁链接):
<table>
<tr>
<th>Title</th>
<th>Content</th>
</tr>
<% for post in @posts %>
<tr>
<td><%= post.title %></td>
<td><%= post.content %></td>
<td><%= link_to "Edit", edit_post_path(post), :class => "edit" %></td>
<!--
This is the problem here... I can't seem to get it to work.
It DOES delete the record, but then gets redirected to /posts/:id
and displays my javascript as html.
-->
<td><%= link_to "Destroy", post , :confirm => 'Are you sure?', :method => :delete, :class => 'destroy' %></td>
</tr>
<% end %>
</table>
销毁.js.erb:
$("#post_errors").hide(300);
$("#flash_notice").html("<%= escape_javascript(flash[:notice])%>");
$("#flash_notice").show(300);
$("#posts_list").html("<%= escape_javascript( render(:partial => "posts") ) %>");
页面加载时加载的 javscript:
// Setting up the ajax requests for the forms/links.
$(document).ready(function() {
$("#new_post").submitWithAjax();
$("a.edit").each(function(){
$(this).getWithAjax();
});
$("a.destroy").each(function(){
$(this).postWithAjax();
});
});
// Setting up ajax for sending javascript requests
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
});
return this;
};
jQuery.fn.getWithAjax = function() {
this.click(function() {
$.get(this.href, null, null, "script");
return false;
});
return this;
};
jQuery.fn.postWithAjax = function() {
this.click(function() {
$.post(this.href, null, null, "script");
return false;
});
return this;
};
要查看我正在使用的所有代码,请查看我发布的另一个问题,但我认为这足以了解我做错了什么。此外,当我运行 chrome 并单击破坏链接时,chrome 会向我显示 javascript 警告:
Resource interpreted as document but transferred with MIME type text/javascript.