【发布时间】:2012-11-18 14:02:24
【问题描述】:
经过一周的谷歌搜索和搜索。我什至很难找到一个关于从数据库表而不是从名为 data.text 的平面文本文件中进行长轮询的教程。目前,我在 data.text 中手动编写任何内容,它会立即出现在浏览器中。
这是问题:使用数据库进行长轮询?即使在 StackOverflow 中也没有正确回答。 (我在这里找到了很多但徒劳无功。)这个例子也在这里 filemtime alternative for MySQL
如何修改 getdata.php 以使其能够从数据库中获取数据?
$sql=mysqli_query($database,"SELECT * FROM messages where time>=$curr_date ORDER by time DESC");
while($row=mysqli_fetch_array($sql)){
$messages=$row['messages'];
$id=$row['id'];
echo $messages;
}
Messages表如下
id fro to mesg time status last_modified
我在这里列出一个例子。 在此示例中,使用了三个文件。
- index.html
- getdat.php
- data.text
是否需要制作第四个文件来从数据库(mysql)获取数据?如果不是,那么需要在 getdata.php 或 data.text 中进行哪些类型的更改才能使用数据库中的动态数据?
这是我的 Javascript
<script type="text/javascript" charset="utf-8">
var timestamp = null;
function waitformsg() {
$.ajax({
type:"Post",
url:"getdata.php?timestamp="+timestamp,
async:true,
cache:false,
success:function(data) {
var json = eval('(' + data + ')');
if(json['msg'] != "") {
$("#messages").append(json['msg']);
}
timestamp = json["timestamp"];
setTimeout("waitformsg()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
setTimeout("waitformsg()", 15000);
}
});
}
$(document).ready(function() {
waitformsg();
});
</script>
这里是getdata.php文件
<?php
include("../model/includes/classes.php");
$filename='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);
?>
【问题讨论】:
-
欢迎来到 Stack Overflow。如果你澄清你的问题,它将帮助你得到答案。您似乎正在创建一个网页(在 Javascript 中也称为客户端应用程序),该网页应该使用 ajax 来轮询您的服务器。似乎您希望对 getdata.php 的第一个 ajax 请求检索已存储在您的表中的所有消息,并希望后续请求检索自最近一次请求以来出现的任何新消息。那是对的吗?另外,请显示您的
messages表的定义。 -
@OllieJones 感谢您的回复。在我看来,您似乎是解决此查询的最后希望。确切地说。我正在使用长轮询技术构建聊天应用程序。Messaes 表只是一个包含 id 的标准聊天表,to,from,message,time 列。
标签: php jquery mysql ajax long-polling