1. [代码] 客户端接收代码 (收到的data是string) var source=new EventSource("server-events.php");source.onmessage=function(event){console.log(JSON.stringify(JSON.parse(event.data)))};source.onopen=function(event){console.log('[.]s
1. [代码]客户端接收代码 (收到的data是string)
var source=new EventSource("server-events.php"); source.onmessage=function(event){ console.log(JSON.stringify(JSON.parse(event.data))) }; source.onopen=function(event){ console.log('[.]start'); }; source.onerror=function(event){ console.log('[.]error'); };
2. [代码]php服务端推送代码
<?php error_reporting(0); require 'req/Mysqlconn.php'; mysql_select_db('TEST_DB',$con); mysql_query('SET NAMES UTF8'); $sql = "SELECT * FROM TEST_TB"; $list = array(); $query = mysql_query($sql); while($r = mysql_fetch_array($query)){ $arraone = array( 'id' =>$r['id'] , 'info' =>$r['info'] ); array_push($list, $arraone); } $back = json_encode($list,JSON_UNESCAPED_UNICODE); header('Content-Type: text/event-stream;charset=utf-8'); header('Cache-Control: no-cache'); echo "data: {$back}\n\n"; flush(); ?>