Laravel内部服务器发送的事件 [英] Server-sent events inside Laravel
问题描述
我正在尝试在Laravel 4内部实现HTML5服务器发送的事件,我发现了这个存储库
I am trying to implement the HTML5 Server-sent events inside Laravel 4, I found this repo
脚本使用server.php
文件使其正常运行.我的问题是我将如何实现它以使其与Controller(而不是普通的php文件)一起工作?因此,在Javascript方面,它看起来像这样:
the script uses server.php
file to get it working. My question is how would I implement it to get it working with a Controller instead of a plain php file? So in the Javascript side it will look like this:
var source = EventSource('/notifications');
我尝试这样做只是为了查看是否得到响应:
I tried this just to see if I get a response:
class NotificationsController extends BaseController {
public function index()
{
$response = Response::view('notifications.index');
$response->header('Content-Type', 'text/event-stream');
$response->header('Cache-Control', 'no-cache');
return $response;
}
}
并在视图中:
<?php
echo "id: 4" . PHP_EOL;
echo "data: this is a message" . PHP_EOL;
flush();
最后,我在google-chrome网络面板中收到此错误:
Finally I get this error in google-chrome network panel:
caution: provisional headers are shown
推荐答案
找到它,解决方案非常简单:
Found it, the solution was quite simple:
主布局中的JavaScript
:
var source = new EventSource('/notifications');
source.onmessage = function(e) {
console.log(e);
}
: in the 我回来了MessageEvent! I got back the MessageEvent ! 这篇关于Laravel内部服务器发送的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!NotificationsController@index
:header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if (true)
{
echo "data: <p> Hello There </p>\n";
}
flush();