我正在php网站上工作,涉及大量数据。 我正在尝试实施彗星而不是简单的ajax民意调查。
每当有人插入数据时,我都会从数据库中获取数据。我有2个PHP页面:
long.php
<script type="text/javascript" >
var lastid = null;
$(document).ready(function(){
lastid = $('.what').children().last().attr('id');
});
var lastid = null;
function waitForMsg(){
lastid = $('.what').children().last().attr('id');
$.ajax({
type:"GET",
url:"pollcheck.php?lastid="+lastid,
async:true,
cache:false,
success: function(data){
$('.what').append(data);
setTimeout('waitForMsg()', 1000);
}
});
}
$(document).ready(function() {
waitForMsg();
});
</script>
和pollcheck.php:
<?php
include('connection.php');
include('config.php');
$lastmodif = isset($_GET['lastid']) ? $_GET['lastid'] : 0;
$queryfetchpollid = "select * from poll where id > $lastmodif";
$resultfetchpollid = mysqli_query($con, $queryfetchpollid);
$num_rows = mysqli_num_rows($resultfetchpollid);
while($num_rows <= 0) {
usleep(10000);
clearstatcache();
$queryfetchpollid = "select * from poll where id > $lastmodif";
$resultfetchpollid = mysqli_query($con, $queryfetchpollid);
while($resultrow = mysqli_fetch_array($resultfetchpollid)){ $lastmodif = $resultrow[0]; }
$num_rows = mysqli_num_rows($resultfetchpollid);
}
while($resultrow = mysqli_fetch_array($resultfetchpollid)){
$lastmodif = $resultrow[0];
echo "<div class='rowt' id='$resultrow[0]'><div class='no'>$resultrow[0]</div><div class='name'>$resultrow[1]</div></div>";
}
?>
当服务器负载至关重要时,这种方法比简单的ajax轮询更好吗? 你知道其他方法吗?
答案 0 :(得分:0)
Ajax轮询对您的服务器进行大量查询。我建议看看chat example
我认为最好选择websockets。
如果您将使用此git repo中的示例,则您的代码将与此类似:
pollcheck.php与现在一样。
在long.php中将是这段代码:
$(document).ready(function() {
// recive last messages from server when page opend
$.ajax({
type:"GET",
url:"pollcheck.php?lastid=0",
async:true,
cache:false,
success: function(data){
$('.what').append(data);
}
});
// subscribe to new messages from websockets
cometApi.start({node:"app.comet-server.ru", dev_id:15 })
cometApi.subscription("simplechat.newMessage", function(event){
$('.what').append(data);
})
})
当您插入数据库中的poll
表时,在插入数据库后添加此代码:
// host login and password from your installation
// of this websockets server https://github.com/CppComet/comet-server
$host = "app.comet-server.ru";
$user = "15";
$password = "lPXBFPqNg3f661JcegBY0N0dPXqUBdHXqj2cHf04PZgLHxT6z55e20ozojvMRvB8";
// Connecting to CppComet api
$comet = mysqli_connect($host, $user, $password, "CometQL_v1");
if(mysqli_errno($comet))
{
echo "Error:".mysqli_error($link);
}
// payload of your message
$msg = Array( "name" => $_POST["name"], "text" => $_POST["text"] );
$msg = json_encode($msg);
$msg = mysqli_real_escape_string($comet, $msg);
// send message to webpage over websockets
$query = "INSERT INTO pipes_messages (name, event, message)" .
"VALUES('simplechat', 'newMessage', '".$msg."')";
mysqli_query($comet, $query);
if(mysqli_errno($comet))
{
echo "Error:".mysqli_error($comet);
}
else
{
echo "ok";
}
在此示例中,将使用CppComet api
向您的网页发送消息