将Facebook中的通知发送到仪表板的理想机制是什么?我认为最好的方法是每5秒对一个php页面进行Ajax调用并检索通知.
有没有更好的方法来做类似的改变?
它也适用于所有移动浏览器.
我是按照以下方式做的,
使用$.post
jQuery中的无刷新页面获取数据.
$.post("page.php",{"act":1},function(data){
$("#id").html(data);
});
in page.php write your query
Run Code Online (Sandbox Code Playgroud)
编辑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();
});
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
编辑2
一切正常,但是当data.txt文件没有发生变化时,我会在50秒内收到这样的错误消息.
错误:超时(超时)
怎么能防止这种情况?
REF:Javascript可变范围
据我所知,基本上有两种方法可以做到这一点:轮询和 websockets。轮询要么每隔一段时间发出许多请求,要么发出一个浏览器和服务器都知道很长的请求(也称为长轮询)。然后是网络套接字。我已经有一段时间没有接触 PHP 领域了,但最后我检查了一下那里并不真正支持 websockets。它可能已经改变了。在 Node 世界中,socket.io 是一个很好的解决方案,它使用 websockets 和长轮询作为备份。
快速搜索发现了 websockets 和 php: http: //socketo.me/docs/
归档时间: |
|
查看次数: |
5124 次 |
最近记录: |