2014-01-28 49 views
0

我有一個會話列表(由發件人分組的多個郵件)。如何提交表單而不跳轉到頁面頂部

我在每次對話下都有一個回覆文本框。

一旦我提交回復(在文本框中填寫一些文本並點擊回覆按鈕),頁面刷新/重定向並跳轉到頁面頂部。

是否可以提交將回復添加到顯示的會話中而不跳轉到頁面頂部的表單?

在我看來,我有

<% @messages.each do |from, message| %> 
<p><%= from %></p> 
<% message.each do |msg| %> 
    <p><%= msg.content %></p> 
<% end %> 

<%= form_for(@message) do |f| %> 
<%= f.text_field :content %> 
<%= f.submit "Reply" %> 
<% end %> 
<% end %> 

在我的控制器我有

def create 
... 
if @message.save 
    redirect_to @business, notice: 'Reply sent.' 
else 
    redirect_to @business, notice: 'Reply could not be sent.' 
end 
end 
+0

調查Ajax。 – jcm

+0

爲此使用jQuery。 :) –

+0

您正在重定向控制器上的頁面。它將永遠在最上面。如果你真的想留在你之前嘗試使用jQuery/Ajax –

回答

1

使用

form_for(@message), remote: true do |f| 

然後在你的控制器(行動創建已進行後的路線)

if @message.save 
    render json: { succ: true, notice: 'Reply sent.'} 
else 
    render json: { succ: false, notice: 'Reply could not be sent.' } 
end 

之後,你必須用JavaScript來處理它,最簡單的方法是使用jQuery做:

$('#container').on('ajax:success', function(event, data){ 
    if (data.succ) { 
    // handle your success somehow, like show a new field 
    // you can use data.notice 
    } else { 
    // something went wrong 
    } 
}) 

希望幫助

看看一個這些jQuery函數:

$('#foo').hide() // hides the element (e.g. form) 

$('#bar').val('') // on input sets value to empty 

$('#msg_container').append('<p>form</p><p>message</p>') 
// adds html to the end of the container 

$('#notice').html(data.notice) 
// changes the contents of the element (e.g. displaying notice) 

這應該足以處理評論,你可以找到更多信息here

哦,不要忘了,如果你喜歡,你可以通過json傳遞更多參數,例如:

render json: { succ: true, notice: 'Reply sent.', from: someone, msg: text} 
+0

這是一個很大的幫助。謝謝。我的jQuery非常糟糕。我可以請求你幫忙處理成功和失敗嗎?我只是想讓新創建的回覆添加到正在顯示的列表的末尾。 – grabury

+0

添加了幾個可能證明有用的jQuery示例函數。 –

相關問題