我正在尝试实现与http://pusher-chat.heroku.com/
类似的功能但是,我无法弄清楚如何在没有页面刷新的情况下调用动作。
页面刷新失败了使用推送器的目的。
到目前为止,我已经创建了一个聊天表,其中包含属性account_id和message。
在我的聊天控制器中,我有以下内容:
def create
account = Account.getAccountById(session[:user])
if params[:message].blank?
@title = "Chat"
@chatLog = Chat.find(
:all,
:order => "created_at ASC",
:limit => 20
)
render :action => :index
else
chatter = Chat.new(
:account_id => account.id,
:message => params[:message]
)
payload = {
"account_id" => chatter.account_id,
"message" => chatter.message
}
if chatter.save
Pusher['chat-channel'].trigger('send_message', payload)
@title = "Chat"
@chatLog = Chat.find(
:all,
:order => "created_at ASC",
:limit => 20
)
render :action => :index
else
render :action => :index
end
end
rescue ActiveRecord::RecordNotFound
reset_session
redirect_to(new_account_path)
end
在我的chat.js文件中,我有以下内容:
$(document).ready(function() {
// Enable pusher logging - don't include this in production
Pusher.log = function(message) {
if (window.console && window.console.log) window.console.log(message);
};
// Flash fallback logging - don't include this in production
WEB_SOCKET_DEBUG = true;
var pusher = new Pusher('62651eca256339fa7fca');
var channel = pusher.subscribe('chat-channel');
channel.bind('send_message', function(chatter) {
$('#loading').show();
});
});
我以前从未建造过这样的东西,所以我很感激任何帮助。
我知道必须涉及更多的javascript。
谢谢,
布赖恩
答案 0 :(得分:0)
要在不刷新的情况下调用操作,您应该使用ajax。
我还没有尝试推送,但似乎每当有人“提交”新消息时,您的应用程序就会发送到推送频道,以便它可以在线广播给每个“订阅”的客户端。
如果这是正确的,你应该考虑整个事情:
当有人点击“新聊天”时,它会创建一个新的聊天室,在推送器上实例化一个新频道并将其保存在数据库中。这将在网址上生成标识,您可以将其发送给某人,以便他们可以加入您的聊天。
在聊天屏幕上,您将有一个用于呈现聊天的大div和您发送消息的输入文本字段。此特定字段将使用ajax您的聊天ID和消息提交给您的应用程序。
当您收到此信息时,在聊天控制器上,您将获得该聊天室数据库中的推送通道ID,在数据库中保存历史消息,并将其发送回与该推送室连接的每个用户。
在聊天中呈现文本的逻辑将由客户端javascript完成。
答案 1 :(得分:-1)
嗯,我的方法是使用一个Javascript计时器,它每隔两秒调用一次AJAX脚本来获取自上次请求以来的新聊天项 - 然后只刷新聊天框。像这样:
var latest_entry_number = 0;
var chatter = window.setInterval("getNewestEntries()",2000);
function getNewestEntries() {
$.ajax({
url: "/path/to/latest_entries",
type: "POST",
dataType: "JSON",
data: {latest_entry: latest_entry_number}
success: appendEntries
});
}
function appendEntries(data) {
latest_entry_number = data.latest_entry;
$.each(data.entries, function(key,val){
//append the entries to the chat
})
}
控制器动作如下所示:
def latest_entries
data[:latest_entry] = get_latest_entry # each entry gets a consecutive, ascending number
data[:entries] = get_entries_since(params[:latest_entry_number]) # get all entries done since that number
# Should be an array
render :json => data
end
或类似的东西。