2013-03-20 103 views
0

我有以下代碼:爲什麼我js.erb不工作

comment.js.erb

alert("Alert"); 

的application.js

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; 
}; 


$(document).ready(function() { 
    $(".comment_form").submitWithAjax(); 
}) 

查看形式:

<% form_for :comment, :url => comment_task_path(tasks.id), 
         :html => {:remote => true, 
         :class => "comment_form"} do |f|-%> 
    <%= f.text_field :remark, :placeholder => "Add Comments", :rows => 2, 
        :class => 'box', 
        :style => "width: 834px; height: 40px;"%> 
    <%= f.submit "Comment"%> 
<% end -%> 

控制器方法:

def comment  
    @comment = Comment.new(params[:comment]) 
    @comment.user_id = @current_user.id 
    @task.comments << @comment 
    flash[:notice] = "thank you" 
    if @comment.save 
    # what code do I put here to render comment.js.erb? 
    else 

    end 
end 

如果我想要comment方法渲染我的comment.js.erb,需要輸入哪些代碼? 我試過render torespond to,但它仍然沒有運行。

+0

請花時間正確縮進您的代碼。你也不會顯示遠程相關的代碼片段。你的表單是':update_status',它與'.comment_form'無關。 – meagar 2013-03-20 04:05:28

+0

對不起,我更新了它。我的錯誤 – 2013-03-20 04:09:31

+0

在'comment.js.erb'文件夾中? '應用程序/視圖/ tasks'?你在development.log中得到什麼錯誤信息? – Mischa 2013-03-20 05:57:56

回答

0

無需渲染comment.js.erb明確。默認情況下,控制器在執行該方法後將呈現comment.js.erb。可能你可以有以下代碼。

評論行動

def comment 
    # ... 
    @comment.save 
end 

,並在comment.js.erb文件

<% if @comment.valid? %> 
    alert("Comment created successfully"); 
<% else %> 
    alert("Something went wrong."); 
<% end %> 
+0

它響應「模板丟失」,但我有同一個文件夾中的comment.js.erb。 – 2013-03-20 04:23:10

+0

仍然我不迴應comment.js.erb – 2013-03-20 04:30:03

+0

該評論正在創建?你可以讓我知道你準確得到的錯誤是什麼? – 2013-03-20 04:36:16

0

您需要將FORM作爲參數傳遞給插件。

jQuery.fn.submitWithAjax = function(elem, options, arg) { 
+0

我不知道,但我已經包括,已經在我的application.js – 2013-03-20 04:16:07

-1

在你的路由添加一個GET請求來獲取comments.js.erb

get'your_controller_name/comments',:as =>'comments'

在您的控制器中使用comments_path

+0

首先,它是一個post請求,而不是獲取請求。其次,如果你讀了評論,你會知道路由不是問題。評論被創建。 – Mischa 2013-03-20 05:54:50