未显示EventSource消息

时间:2015-01-19 07:53:52

标签: javascript php

我尝试了js eventsource和PHP的示例。它在本地工作正常,但当我将它发送到远程服务器时,该消息仅在php进程完成后显示。可以帮我解决这个问题吗? 这是代码。 PHP。

<?php
header('Content-Type: text/event-stream');
// recommended to prevent caching of event data.
header('Cache-Control: no-cache'); 

function send_message($id, $message, $progress) {
    $d = array('message' => $message , 'progress' => $progress);

    echo "id: $id" . PHP_EOL;
    echo "data: " . json_encode($d) . PHP_EOL;
    echo PHP_EOL;

    ob_flush();
    flush();
}

//LONG RUNNING TASK
for($i = 1; $i <= 10; $i++) {
    send_message($i, 'on iteration ' . $i . ' of 10' , $i*10); 
    sleep(1);
}

send_message('CLOSE', 'Process complete');

HTML / JS。

<html>
<head>
</head>
<body>
<ul id="eventlist"></ul>
</body>
<script>
  var eventList = document.getElementById('eventlist');
  var evtSource = new EventSource("ssedemo.php");
  evtSource.onmessage = function(e) {
    var newElement = document.createElement("li");
    newElement.innerHTML = "message: " + e.data;
    //console.log(eventList);
    //console.log("hello");      
    eventList.appendChild(newElement);
  }
</script>
</html>

0 个答案:

没有答案