将像Facebook这样的通知发送到仪表板的理想机制是什么?我认为最好的方法是每5秒对一个php页面进行Ajax调用并检索通知。
有没有更好的方法来进行类似的更改?
它也应该适用于所有移动浏览器。
我正在按照以下方式进行操作,
在jQuery中使用$.post
获取数据而无需刷新页面。
$.post("page.php",{"act":1},function(data){
$("#id").html(data);
});
in page.php write your query
编辑1
在引用一些在线笔记及其实时工作之后,我编写了这样的函数。
var TimeStamp = null;
function waitForMsg() {
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + TimeStamp,
async: true,
cache: false,
timeout: 50000, /* Timeout in ms */
// data: "TimeStamp=" + TimeStamp,
success: function( data ) {
var json = eval('(' + data + ')');
if ( json['msg'] != "" ) {
alert( json['msg'] );
}
TimeStamp = json['timestamp'];
setTimeout(
'waitForMsg()', /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {
alert("error:" + textStatus + "(" + errorThrown + ")");
setTimeout(
'waitForMsg()', /* Try again after.. */
"15000"); /* milliseconds (15seconds) */
},
});
}
;
// calling after dom is ready
$(document).ready(function() {
waitForMsg();
});
PHP文件是
<?php
$filename = dirname(__FILE__).'/data.txt';
$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);
编辑2
一切正常,但是当data.txt文件没有发生任何变化时,我在50秒内收到一条错误消息。
错误:超时(超时)
如何预防呢?
引用:Javascript Variable Scope
最佳答案
据我所知,基本上有两种方法可以做到这一点:轮询和websocket。轮询要么是每隔一个间隔发出多个请求,要么是浏览器和服务器知道很长的请求很长(也称为长轮询)。然后是websockets。我已经有一段时间没有去过PHP了,但是最后我检查了websockets在那里并没有得到真正的支持。它可能已经改变了。在Node world中,socket.io是一个很好的解决方案,它使用websocket和长轮询作为备份。
快速搜索找到了websockets和php:
http://socketo.me/docs/
关于php - 通知而无需重新加载页面(例如Facebook或google plus通知),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19353629/