我正在使用Server-Sent Event将数据从核心php发送到html,并且运行正常。
我使用了参考http://www.w3schools.com/html/html5_serversentevents.asp中的示例
但是,当我尝试使用restful apis在CakePHP中做同样的事情时,它产生了问题。
下面是我的代码:
控制器:sseController.php
public function sseTest() {
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
$this->set('finalData',"data: The server time is: {$time}\n\n");
}查看:sse_view.ctp
<?php
echo json_encode($finalData);
flush();
?> HTML调用api是...
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource('http://localhost/b2c/api/reports/sseTest');
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}请给我一些建议。
发布于 2014-05-29 12:45:09
您正试图在视图中json_encode无效的JSON,这可能会给您带来问题。
"data: The server time is: {$time}\n\n" // this is not JSON您需要根据HTML5 Server-Sent Events docs in w3schools删除json_encode来更改视图
视图sse_view.ctp将如下所示:
<?php
echo $finalData;
flush();
?> 发布于 2014-05-29 14:50:30
更新:我已经在我的本地试用过了,这是有效的!
控制器: sseController.php
public function sse_test() { //change your function to this (cakePHP standards)
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
$this->set('finalData',"data: The server time is: {$time}\n\n");
}
public function sse_view(){ //add this one
}查看: sse_view.ctp
<div id="result"></div>
<script tye="text/javascript">
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource('<?php echo "http://localhost{$this->base}/reports/sse_test";?>'); //you must check this one if the path is correct (modify if not correct or try to alert it)
// alert('<?php echo "http://localhost{$this->base}/reports/sse_test";?>'); //uncomment to check if your using the correct path
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br>";
};
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}在sse_view.ctp: sse_test.ctp的相同路径下创建一个文件
<?php
echo $finalData;
flush();
?> 发布于 2017-01-31 15:45:33
将此代码更改为
$this->layout = false;在控制器操作函数中
https://stackoverflow.com/questions/23925770
复制相似问题