我正在玩一些推送通知,并且希望在数据库发生更改时更新页面。
我有这个来自http://www.screenr.com/SNH:
<?php
$filename = dirname(__FILE__).'/data.php';
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
我的 data.php 是一个从 JSON 文件中获取数据的脚本:
<script>function itnews_overview() {
$.getJSON('/ajax.php?type=itnews_overview', function(data) {
$.each(data.data, function(option, type) {
$('.bjqs').append('<li><span class="date">'+ type.submitted +'<br />'+ type.time +'</span><h2>' + type.title + '</h2><p>' + type.content + '</p></li>');
});
});
}
</script>
<script>
itnews_overview();
</script>
<div id="news">
<ul class="bjqs"></ul>
</div>
更新:来自 index.php 的代码:
<script type="text/javascript">
var timestamp = null;
function waitForMsg() {
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data) {
var json = eval('(' + data + ')');
if(json['msg'] != "") {
$(".news").html(json['msg']);
}
timestamp = json['timestamp'];
setTimeout('waitForMsg()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout('waitForMsg()',15000);
}
});
}
$(document).ready(function(){
waitForMsg();
});
</script>
由于当我向数据库添加内容时未保存此文件,因此 filemtime 将不起作用 - 是否有另一种方法可以检查是否已将新行添加到表中?
更新:试图用 SSE 解决这个问题。我有两个文件,index.php 和 send_sse.php(灵感来自http://www.developerdrive.com/2012/03/pushing-updates-to-the-web-page-with-html5-server-sent-events / )
索引.php:
<div id="serverData">Content</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("send_sse.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>
发送_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$url = "content.json";
$str = file_get_contents($url);
$data = json_decode($str, TRUE);
//generate random number for demonstration
//echo the new number
echo "data: " . json_encode($data);
ob_flush();
?>
但是,这似乎不起作用,这可能是因为 SSE 需要纯文本数据。我只是不知道如何做到这一点,然后将该内容包装在几个 HTML 标记中。
更新:好的,现在它可以与 SSE 合作,这要感谢 VDP。我有以下内容:
$sql= "SELECT title, content, submitted FROM `flex_itnews` where valid = 1 order by submitted desc";
$query= mysql_query($sql);
setlocale(LC_ALL, 'da_DK');
while($result = mysql_fetch_array($query)){
echo "data: <li><span class='date'>". strftime('%e. %B', strtotime($result['submitted'])) ."<br />kl. ". strftime('%H.%M', strtotime($result['submitted'])) ."</span><h2>" . $result['title']. "</h2><p>" . $result['content'] ."</p></li>\n";
}
但是,当我添加任何新内容时,它只是 echo data: data: data
。如果我刷新页面,它会正确显示。
更新:使用 livequery 插件:
<script>
var source = new EventSource('data2.php');
source.onmessage = function (event) {
$('.bjqs').html(event.data);
};
$('#news').livequery(function(){
$(this).bjqs({
'animation' : 'slide',
'showMarkers' : false,
'showControls' : false,
'rotationSpeed': 100,
'width' : 1800,
'height' : 160
});
});
</script>
更新:尝试使用委托()
<script>
$("body").delegate(".news", "click", function(){
$("#news").bjqs({
'animation' : 'slide',
'showMarkers' : false,
'showControls' : false,
'rotationSpeed': 100,
'width' : 1800,
'height' : 160
});
var source = new EventSource('data2.php');
source.onmessage = function (event) {
$('.bjqs').append(event.data);
};
});
</script>