var EventSource = window.EventSource || window.MozEventSource;実は、EventSourceオブジェクトは、すべてのブラウザでこの名前のオブジェクトとして用意されているわけではありません。FirefoxなどのMozilla系ブラウザでは、window.MozEventSourceとして、それ以外のブラウザではwindow.EventSourceとして用意されているのです。そこで、このどちらかをEventSourceに設定するようにしてあるのですね。
if (event.data == "Bye"){
event.target.close();
alert('終了しました。');
}event.dataが"Bye"だった場合には、event.targetの「close」を呼び出しています。このevent.targetには、メッセージが送信されてきたEventSourceオブジェクトが設定されています。そのcloseを呼び出すことで、サーバーとの接続を終了することができるのです。※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
※HTML側
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>タイトル</title>
<style>
h1 { font-size: 14pt; padding: 1px 10px;
border-style: solid; border-width: 0px 0px 2px 7px; border-color:green; }
body { background: #EEFFEE; }
article { background: white; margin: 10px 0px; padding: 10px; }
</style>
<script type="text/javascript">
var EventSource = window.EventSource || window.MozEventSource;
function initial(){
if (!EventSource){
alert("EventSourceが利用できません。");
return;
}
var source = new EventSource('event.php');
source.onmessage = function(event){
var ol = document.getElementById('msgs');
ol.innerHTML = '<li>' + event.data + '</li>' + ol.innerHTML;
if (event.data == "Bye"){
event.target.close();
alert('終了しました。');
}
};
}
</script>
</head>
<body onload="initial();">
<header>
<h1>Sample</h1>
</header>
<article>
<ol id="msgs"></ol>
</article>
</body>
</html>
| << 前へ | 次へ >> |