2012-02-10 83 views
1

我遇到問題。當表單驗證失敗時,我需要調用javascript函數。 我正在嘗試這樣做。這是我在comment_controller中的創建操作。如果驗證失敗,請致電javascript

def create 
    p params 
    @comment = parent.comments.build(params[:comment].merge(:ip => request.remote_ip)) 
    if @comment.save 
     redirect_to @page.url, :notice => "grats" 
    else 
     @country = @page.country 
     @city = @page.city 
     respond_to do |format| 
     format.html { render :template => "pages/show" } 
     format.js { render "pages/show" } 
     end 
    end 
    end 

和頁/ show.js.erb有代碼

$('.main').fadeOut(5000); 

,但它不工作。我已經嘗試了另一個js代碼,但它不工作。我做錯了什麼?

回答

0

你試過的其他js代碼是什麼?

最簡單的事情應該是這樣的:

alert("foo"); 

是否一個HTML元素類「主」存在呢? (看看你的源代碼)

你的迴應是否真的呈現show.js.erb文件?你的服務器日誌會告訴你。

Rendered portal/cart_items/update.js.erb (38.4ms) 
Completed 200 OK in 650ms (Views: 51.3ms | ActiveRecord: 6.5ms) 

第一行是典型的ajax響應。

FireBug將幫助你看到服務器端發生了什麼。

+0

我有一個main類的元素。 'alert(「foo」);' ( – 2012-02-10 16:22:31

+0

)所以你很可能不會渲染js,你在production.log中說的是什麼(你可以看看log/production.log或者終端中的服務器輸出嗎?當然你把它叫做ajax?你的鏈接或JS看起來實際上是請求? – 2012-02-10 16:27:29

+0

它只在佈局/應用程序中有Rendered pages/show.html.erb我不知道它爲什麼沒有show.js.erb – 2012-02-10 16:29:07

-1

我想你想重定向到你嘗試添加註釋的頁面?

如果是這樣,嘗試

else 
    @country = @page.country 
    @city = @page.city 
    flash[:errors] = "Your error message..." 
    redirect_to @page 
end 

雖然我建議做一個基本的驗證在JavaScript上之前,使得顯示的錯誤更容易的客戶端。

+0

我正在渲染頁面,我嘗試添加評論。我想用jQuery通知插件在其上顯示錯誤消息。所以我需要使用JavaScript。但我不知道如何 – 2012-02-10 16:41:40