一、前台

<script>//D:\wamp\www\node\xiangmuer\views\main
// var source = new EventSource('http://127.0.0.1:1111/api/ceshi');

function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
$(function(){
$(".title").html(decodeURI(escape(GetQueryString('title'))));
var source = new EventSource("/app/index.php?i="+GetQueryString('i')+"&j=11&c=entry&rid="+GetQueryString('rid')+"&do=daping_show_api&m=fm_photosvote");
//var div = document.getElementById('example');

source.onopen = function (event) {
console.log(event)
//div.innerHTML += '<p>Connection open ...</p>';
};

source.onerror = function (event) {
console.log(event)
//div.innerHTML += '<p>Connection close.</p>';
};

source.addEventListener('connecttime', function (event) {
console.log(event)
//div.innerHTML += ('<p>Start time: ' + event.data + '</p>');
}, false);

source.onmessage = function (event) {//返回成功的

//div.innerHTML += ('<p>Ping: ' + event.data + '</p>');
//cons(event);
var daList=event.data;

var daListJs= JSON.parse(daList);

 

$("#list").html('');
for(var i=0;i<daListJs.length;i++){
var new_zhi = daListJs[i].photosnum
var max = daListJs[i].max
var width = new_zhi/max *100 +'%'
var html ='<li class="clearfix">'
html+='<div class="tem">'+daListJs[i].realname+'</div>'
html+='<div class="barBox">'
html+='<div class="bar" style="width:'+width+'">'+daListJs[i].photosnum+'</div>'
html+='<i></i></div></li>'
$(html).appendTo("#list");
}

};

})


</script>

 

 

二:后台php

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // 建议不要缓存SSE数据
global $_GPC,$_W;
$rid=(int)($_GPC['rid']);
$list=pdo_fetchall("SELECT photosnum+xnphotosnum as photosnum,realname from ".tablename('fm_photosvote_provevote')." where rid=$rid order by photosnum desc");
$listt=pdo_fetchall('select MAX(photosnum+xnphotosnum) from '.tablename('fm_photosvote_provevote')." where rid=$rid");
$max=$listt[0]['MAX(photosnum+xnphotosnum)'];
foreach ($list as &$value) {
$value['max']=$max;
}
$list=json_encode($list);
$time = date('Y-m-d H:i:s');
echo 'retry: 1000'.PHP_EOL;//返回时间间隔
echo 'data:'.($list).PHP_EOL.PHP_EOL;

 

 

node.js端后台

router.get('/ceshi',function(req,res,next){
res.writeHead(200, {
"Content-Type":"text/event-stream",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
"Access-Control-Allow-Origin": '*',
});
res.write("retry: 10000");
res.write("retry: 10000");
res.write("retry: 10000");
res.write("retry: 10000");
// interval = setInterval(function () {
// res.write("data: " + (new Date()) + "\n\n");
// }, 1000);
//res.send('uapi你妹');
});