我正在尝试使用Event Wource API& amp;来实现基本的Rails 4代码。动作控制器直播。一切都很好,但我无法接触到事件听众。
控制器代码:
class HomeController < ApplicationController
include ActionController::Live
def tester
response.headers["Content-Type"] = "text/event-stream"
3.times do |n|
response.stream.write "message: hellow world! \n\n"
sleep 2
end
end
Js代码:
var evSource = new EventSource("/home/tester");
evSource.onopen = function (e) {
console.log("OPEN state \n"+e.data);
};
evSource.addEventListener('message',function(e){
console.log("EventListener .. code..");
},false);
evSource.onerror = function (e) {
console.log("Error State \n\n"+e.data);
};
当我重新加载页面时,我的控制台输出是“OPEN state”&amp;然后“错误状态”。事件侦听器代码未显示。
当我卷曲页面时,“消息:Hellow world!”正在显示。
我在development.rb中更改了
config.cache_classes = true
config.eager_load = true
我的浏览器是chrome&amp; firefox是最新版本,因此没有问题
我失踪的地方?建议请!
答案 0 :(得分:1)
服务器发送事件的事件格式为
"data: message text\n\n"
所以,在你的情况下它应该是:
response.stream.write "data: hello world! \n\n"
检查this MDN page以供参考。