我正在尝试在网页上推送一个简单的div
元素的新内容(内容由2个iFrame
组成)。我已经密切关注在线教程。
设置为:
$_REQUEST
中传递。
div
的目标html页面。它具有一个JavaScript,用于设置PHP文件的侦听器。 当切换按钮调用PHP文件时,PHP文件将在浏览器窗口中打开,并显示我希望目标窗口接收的文本。目标页面中的侦听器似乎未收到该消息。 (我定义了text/event-stream
和no-cache headers
。)
这是一个非常小的应用程序,并且紧跟教程。这些页面由Raspberry Pi上的apache2和PHP 7提供服务。我觉得我缺少一些简单的东西。
在index.html
中,应该用收到的文本替换div
的内容:
<div id="serverData"> ...(2 iframes)... </div>
...
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("ViewController.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
在ViewController.php
中,更新源:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//stream new webpages to the main view
$myPDO = new PDO('sqlite:/home/pi/pi_DB');
if (isset($_REQUEST['pageNo']) ) {
$result = $myPDO->query("SELECT htmlContent FROM views WHERE pageID = " . $_REQUEST['pageNo']);
$queryResult = $result->fetch(PDO::FETCH_ASSOC);
echo "event: message\n"; // same result with or without this line
echo "data: " . $queryResult['htmlContent'] . "\n\n";
flush();
}
在viewswitcher.html
中,该按钮具有用于选择不同内容的按钮:
<p>
<button class="button" onclick="swapViewIntoIndex(2)">Select View 2</button>
</p>
<script>
function swapViewIntoIndex(viewNumber) {
// load ViewController.php and pass it the button (view) number
switch (viewNumber) {
case 1:
var url = 'ViewController.php?pageNo=1';
window.location.href = url;
break;
case 2:
var url = 'ViewController.php?pageNo=2';
window.location.href = url;
break;
default:
}
}