我知道长轮询是使聊天更新其内容的最佳方式,我知道网络套接字,但我认为长轮询是最好的,因为许多浏览器不支持网络套接字。问题是我不知道如何编写长轮询脚本,我有一个常规的ajax和常规的php get和post脚本,所以我怎样才能使这个PHP代码和ajax代码以长轮询方式工作? (我不希望它继续请求每一秒我希望它回应来自数据库的任何新消息......)
这是我的ajax代码: -
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: 'ajax/ajax/chat.php',
type: 'POST',
data: { method: 'fetch' },
success: function(data) {
$('#chats').html(data);
$('#chatshere').scrollTop($('#chatshere')[0].scrollHeight);
}
});
}
chat.interval = setInterval(chat.fetchMessages, 1000);
chat.fetchMessages();
这是我的PHP代码: -
<?php
require '../core/init.php';
if(isset($_POST['method']) === true && empty($_POST['method']) === false) {
$chat = new Chat();
$method = trim($_POST['method']);
if($method === 'fetch') {
$messages = $chat->fetchMessages();
if(empty($messages) === true) {
echo 'There is no any messages !';
}
else
{
foreach($messages as $message) {
$log_username = $_SESSION['username'];
if($message['user1'] == $log_username){
?>
<ul class="mychat">
<li class="first">
<div class="sOutline">
<div class="suser">
<a href="#">
<img style="height:30px; width:30px;" title="belowfs" alt="belowfs" class="profilepic-belowfs" src="http://demo.scritterscript.com/images/membersprofilepic/thumbs/default-s.jpg">
</a>
</div>
</div>
</li>
<li style="margin-left:-5px;">
<div style="border:1px solid #0099CC; border-radius:5px; background:#0099CC; color:#FFFFFF; padding:7px; max-width:165px;">
<?php echo nl2br($message['message']); ?>
</div>
</li>
</ul>
<?php
}else if($message['user2'] == $log_username){
?>
<ul style="float:right;" class="hischat">
<li class="first">
<div class="sOutline">
<div class="suser">
<a href="#">
<img style="height:30px; width:30px;" title="belowfs" alt="belowfs" class="profilepic-belowfs" src="http://demo.scritterscript.com/images/membersprofilepic/thumbs/default-s.jpg">
</a>
</div>
</div>
</li>
<li style="margin-right:-5px;">
<div style="border:1px solid #999; border-radius:5px; background:#999; color:#FFFFFF; padding:7px; max-width:165px;">
<?php echo nl2br($message['message']); ?>
</div>
</li>
</ul>
<?php
}
}
}
}
else if($method === 'throw' && isset($_POST['message']) === true) {
$message = trim($_POST['message']);
if(empty($message) === false) {
$chat->throwMessage($_SESSION['user'], $message);
}
}
}
?>
非常感谢...
答案 0 :(得分:2)
chat.interval = setInterval(function(){chat.fetchMessages()}, 5000);
而不是
chat.interval = setInterval(chat.fetchMessages, 1000);
每5秒获取一次消息。 Rest取决于您的PHP代码以回显新消息。
答案 1 :(得分:1)
这是一个清楚解释不同方法的链接:
What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?
Long-Polling系统:
如果有一个获取消息的间隔,您可能需要查看Ajax Polling部分。