Javascript不是在脚本中呈现而是作为html呈现

这个问题是我昨天问过的一个问题,它涉及将模型的创建/编辑function移动到其索引页面上。 我遇到的最后一个问题是,当我去删除模型时,我有一些应该运行的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 

我的post部分列表(其中包含我所指的销毁链接):

 
Title Content
"edit" %> 'Are you sure?', :method => :delete, :class => 'destroy' %>

destroy.js.erb:

 $("#post_errors").hide(300); $("#flash_notice").html(""); $("#flash_notice").show(300); $("#posts_list").html(" "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并单击destroy链接时,chrome会向我显示一条javascript警告:

 Resource interpreted as document but transferred with MIME type text/javascript. 

这个问题的答案是在请求标头中, Accept标头应该已经设置为text/javascript或类似的东西。 这应该在这个js函数中完成:

 jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }); 

对于POST请求,这种情况发生得很好,但是当我想要执行PUT请求或DELETE请求时,不会以某种方式调用它或者它被忽略。 我意识到需要引用jQuery / AJAX的rails.js插件,因为我使用的是HTML5。

为了使编辑和删除工作,我对link_to方法执行了此操作:

 link_to "Edit", edit_post_path(post), "data-remote" => 'true', 'data-method' => 'get' link_to "Destroy", post , "data-confirm" => 'Are you sure?', "data-remote" => 'true', "data-method" => 'delete' 

将这些html属性添加到我的锚标签允许rails.js确定我想用它们做一些ajax请求。 他们之后开始工作。

手动设置MIME类型可能是问题的根源。 JavaScript通常作为application/x-javascript而不是text/javascript因此最好将其留给渲染引擎来为您设置。

对于像这样的简单情况,使用.js.rjs可能会更好,因为它使您的JavaScript在很大程度上与框架无关。

我遇到了同样的问题。 解决方案是使用此处提供的脚本: http : //www.danhawkins.me.uk/2010/05/unobtrusive-javascript-with-rails-2-3-5/
在按照描述使用它之后,你所要做的就是删除一个对象,就是使用与此代码类似的东西:

  <%= link_to "Destroy", post , :confirm => 'Are you sure?', :class => 'remote destroy' %> 

对我来说,这就像一个魅力。