由于没有彻底理解服务器发送事件(SSE),导致犯了很多错误,无法正确得到预期结果,纠结了很久,现在把注意的东西记下,方便以后查看
<?php
header('Content-Type: text/event-stream'); //注意设置输出内容的类型为text/event-stream,否则会报错
//header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n"; //注意格式,"data: " 开头,结尾"\n\n";
//flush();
?>
<!DOCTYPE html>
<html>
<head>
<title>ajax test</title>
<script src="ajax.js" type="text/javascript"></script>
</head>
<body>
<form action="#">
<input id="btn" type="button" value="登陆"></input>
<div id="msg"></div>
</form>
</body>
</html>
window.onload=function(){
var source=new EventSource("data.php");
source.onmessage=function(event)
{
document.getElementById("msg").innerHTML+=event.data + "<br />";
};
}
特别要注意服务器返回内容的格式。
参考资料:http://www.w3school.com.cn/html5/html_5_serversentevents.asp