[英]Rails chat update in real-time (AJAX or WebSokets)
美好的一天。 我對Rails真的很陌生,我正在嘗試找到在聊天窗口中自動更新消息列表的方法。
我將描述我得到的:
<input type="text">
,每次按下發送按鈕時,該<input type="text">
都會保存到mysql數據庫中。 我想要做的是:當2個人正在輸入/發送他們的消息時,兩個人都將從db中自動更新,而無需刷新頁面或按Send按鈕。 如果user_1發送,則user_2將自動接收它。
我需要一些如何刷新此變量的方法:
<%=@date[i][1]%>
<%=@message[i]%>
我已經讀過有關AJAX長輪詢和WebSockets的信息,但我一無所知。
main.html.erb:
<table class="table">
<thead>
<tr>
<th style="width: 10%">Time</th>
<th style="width: 90%">Message</th>
</tr>
</thead>
<tbody>
<% for i in 0..4 %>
<tr>
<td ><div class="well well-sm"><%=@date[i][1]%></div></td>
<td ><div class="well well-sm"><%=@message[i]%></div></td>
</tr>
<% end %>
</tbody>
</table>
控制器:
def main
if(session[:isLogin]!=true)
redirect_to :controller => 'auth', :action => 'index'
end
@mess_count = 5
@output = Chat.last(@mess_count)
@message = []
@date = []
for i in 0..@mess_count-1
@date[i] = @output[i][:date].to_s.split(' ')
@message[i] = @output[i][:message]
end
PS我知道我的代碼很爛,但是我只需要實時聊天消息更新的一般想法。 謝謝。
ActionCable是一個Websockets框架,用於使用Rails開發實時應用程序。 它是由Rails核心團隊開發的,有傳言稱它將包含在Rails 5中。
您已經可以嘗試一下-但您應該准備好進行大量閱讀-websockets可能會令人生畏,並且需要對javascript和客戶端/服務器交互有很好的了解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.