お世話になっております。
表題の件ですが、jsがほとんどわからないため、行き詰っております。
そもそもSSEを用いてブラウザ更新ということが可能なのかどうかもわかっていない状況です。
よろしくお願いいたします。
###前提
- 特定のモニターに常に全画面表示されている
index.php
がある - index.phpはDBの情報を読んで表示している
- 管理画面上からDBにデータを挿入することができる
- ネットが不安定なこともあるので、一定時間で自動更新する拡張等は使わない
実現したいこと
- 管理画面で変更が行われたらF5等の更新作業なしで該当のブラウザを更新したい
- サーバーの環境や既存のシステムを作り替えることはできないのでServer-Sent Eventsをつかってブラウザを更新させたい
###該当のソースコード
php
1// index.php 2<?php 3include_once 'pdo.php'; 4 5$sql = "SELECT * FROM comment"; 6$res = $conDB->pdoQuery($sql); 7foreach($res as $val){ 8 $html.= "<li>".$val["id"].":<span>".$val["comment"]."@".$val["system_dt"]."</span></li>"; 9} 10 11include_once 'index.html';
html
1<!--index.html--> 2<!doctype html> 3<html lang="ja"> 4<head> 5 <meta charset="UTF-8"> 6 <title>販売状況</title> 7 <script> 8 var evtSource = new EventSource("sse.php"); 9 evtSource.addEventListener("reload",function(e){ 10 window.location.reload(true); 11 }); 12 </script> 13</head> 14<body> 15 <ul> 16 <?=$html?> 17 </ul> 18</body> 19</html>
html
1<!--edit.html(管理画面)--> 2<!doctype html> 3<html lang="ja"> 4<head> 5 <meta charset="UTF-8"> 6 <title>Document</title> 7</head> 8<body> 9 <form method="post" action="sse.php"> 10 <input type="text" name="comment"/> 11 <input type="submit" value="on" name="update" /> 12 </form> 13</body> 14</html>
php
1// sse.php 2<?php 3include_once 'pdo.php'; 4if ($_POST["update"]) { 5 $comment = filter_input(INPUT_POST, "comment"); 6 $sql = "INSERT INTO comment (comment,system_dt) VALUES (?,?)"; 7 $arr = [$comment, date("YmdHis")]; 8 $res = $conDB->pdoPrepare($sql, $arr, 2); 9 10 if($res == true){ 11 header("Content-Type: text/event-stream\n\n"); 12 header('Cache-Control: no-cache'); 13 echo "event: reload\n"; 14 echo "\n\n"; 15 ob_flush(); 16 flush(); 17 } 18}
###試したこと
上記のソース類を分けてincludeしてみたりはしたのですが、うまくいきませんでした。
DBにはきちんとデータが格納されており、手動でindex.phpを更新すれば問題なく表示されます。
###補足情報(言語/FW/ツール等のバージョンなど)
ブラウザ:Google Chrome 54.0
PHP 7.0.13
https://developer.mozilla.org/ja/docs/Server-sent_events/Using_server-sent_events
にあるサンプルコードは動きました。
あなたの回答
tips
プレビュー