[英]Long polling with jquery/ajax on server side
我正在对一个页面中的多个页面进行长时间轮询。 问题是,当我有一个新请求时,它会首先完成上一个请求,尽管当有新请求时,我会中止上一个请求。
这是我的jQuery代码:
var stopped = 1;
var request = 0;
$(document).ready(function () {
$("#leftsec img").click(function () {
stopped = 0;
$("#leftsec img").each(function () {
$(this).attr({
src: 'images/' + this.id + '.gif'
});
$(this).hover(
function () {
$(this).attr("src", 'images/' + this.id + '_over.gif');
}, function () {
$(this).attr("src", 'images/' + this.id + '.gif');
});
});
$(this).attr({
src: 'images/' + this.id + '_over.gif'
});
$(this).hover(function() {
$(this).attr("src", 'images/' + this.id + '_over.gif');
}, function () {
$(this).attr("src", 'images/' + this.id + '_over.gif');
});
location.hash = '!' + this.id;
var topname = document.getElementById(this.id + '1').innerHTML;
$("#tophead").html(topname);
if(request != 0) {
request.abort();
}
var a = this.id;
$.ajax({
url: "no.php",
success: function (result) {
$.ajax({
url: "some.php?id=" + a,
success: function (result) {
$("#centerdata").html(result);
stopped = 1;
rec_fun(a);
}
});
}
});
});
if (window.location.hash != '') {
var hashvalue = window.location.hash;
hashvalue = hashvalue.split('!');
hashvalue = hashvalue[1];
$('#' + hashvalue).click();
} else {
$('#home').click();
}
});
function rec_fun(a) {
//alert('');
if (stopped == 1) {
request = $.ajax({
url: "some.php?id=" + a,
success: function (result) {
$("#centerdata").html(result);
rec_fun(a);
}
});
}
else {
return false;
}
}
我的HTML:
<div class="leftsec" id="leftsec">
<img id='home' class="" src="images/home.gif" onmouseover="this.src='images/home_over.gif'" onMouseOut="this.src='images/home.gif'" /><br />
<div id="home1" align="center" style="font-size:16px; font-family:Verdana;">Home</div>
<img id='school' class="" src="images/school.gif" onMouseOver="this.src='images/school_over.gif'" onMouseOut="this.src='images/school.gif'" /><br />
<div id="school1" align="center" style="font-size:16px; font-family:Verdana">My School</div>
</div>
some.php:
if($_GET['id'] == 'home') {
$main = 'home';
for($i = 0; $i < 30; $i++) {
$word .= $main . "<br>";
}
}
if($_GET['id'] == 'school') {
$retschool = 0;
while($retschool != 1) {
// Look for an update
// If no update found sleep for 2 seconds
}
}
当我单击学校图像后单击家庭图像时,即使我使用了request.abort(),在进行家庭图像请求之前也需要一段时间(完成第一个请求)。 如果我不使用request.abort(),则它会花费相同的时间,并给我一个超时错误,然后处理本地图像请求。 如何使它快速忽略先前的ajax请求,以便它将快速转到新请求并对其进行处理。
我从这个问题中弄清楚了: 长轮询锁定了其他AJAX调用 ……-php锁定给定的会话,直到页面加载完成,因此第二个ajax调用无法通过。 您必须通过调用session_write_close();
来释放锁session_write_close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.