长轮询使用jQuery和PHP [英] Long Polling using jQuery and PHP
本文介绍了长轮询使用jQuery和PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,我一直在试图做使用jQuery库和PHP长轮询。我这样做,所以我可以在未来的某种实时通知系统。在code我现在已经没有真正的工作。
的index.php
< HTML>
< HEAD>
<冠军>长轮询< /标题>
<脚本类型=文/ JavaScript的SRC =HTTP://$c$c.jquery.com/jquery-1.6.2.min.js'>< / SCRIPT>
<脚本类型=文/ JavaScript的'>
$(文件)。就绪(函数(){
的getData();
});
功能的getData(){
$阿贾克斯({
键入:POST,
网址:ajax.php
异步:真正的,
超时:50000,
数据:得=真,
成功:功能(数据){
$(#信息)追加(数据);
的setTimeout(的getData(),1000);
}
});
}
< / SCRIPT>
< /头>
<身体GT;
< DIV ID ='信息'>< / DIV>
< /身体GT;
< / HTML>
Ajax.php
< PHP
如果(兰特(1,100)%2){
回声偶;
} 其他 {
睡眠(兰特(1,4));
}
?>
解决方案
尝试使用本作ajax.php
< PHP
如果(兰特(1,100)%2){
回声甚至与LT; BR />';
} 其他 {
睡眠(兰特(8,12));
}
?>
看这个,有时你必须等待12秒
如果你让在一秒钟内似乎被打破了他来完成,但它不是
So, I've been trying to do Long-Polling using the jQuery Library and PHP. I'm doing this so I can make some sort of real-time notifications system in the future. The code I have now isn't really working.
index.php
<html>
<head>
<title>Long Polling</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
getData();
});
function getData() {
$.ajax({
type: "POST",
url: "ajax.php",
async: true,
timeout: 50000,
data: "get=true",
success: function(data) {
$("#info").append(data);
setTimeout("getData()", 1000);
}
});
}
</script>
</head>
<body>
<div id='info'></div>
</body>
</html>
Ajax.php
<?php
if(rand(1, 100) % 2) {
echo 'even';
} else {
sleep(rand(1, 4));
}
?>
解决方案
Try to use this for ajax.php
<?php
if(rand(1, 100) % 2) {
echo 'even<br />';
} else {
sleep(rand(8, 12));
}
?>
watch this and sometimes you have to wait up to 12 seconds
if you let him to complete in one second it appears to be broken, but it's not
这篇关于长轮询使用jQuery和PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文