【发布时间】:2011-04-15 04:04:58
【问题描述】:
我想知道是否可以使用 $.getJSON 进行长轮询以及正确的前端和后端逻辑是什么。
到目前为止,我已经提出了这个想法,但还没有测试它,因为我很确定存在错误和/或缺少逻辑。
这里是 JS:
function lpOnComplete(data) {
console.log(data);
if (!data.success) {
lpStart();
}
else {
alert("Works!");
}
};
function lpStart() {
$.getJSON("http://path.to.my.URL.php?jsoncall=?", function(data) {
// What happens when no data is returned
// This is more than likely since there
// is no fall back in the PHP.
lpOnComplete(data);
});
};
PHP:
$time = time();
while((time() - $time) < 30) {
// only returns data when it's new.
$data = checkCode();
// What would be the proper way to break out
// and send back $data['success'] = false
// so the JS loop can continue?
if(!empty($data)) {
echo $_GET["jsoncall"] . "(" . json_encode($data) . ")";
break;
}
usleep(25000);
}
【问题讨论】:
-
顺便说一句,
$.getJSON("...", function(data) { lpOnComplete(data); })可以缩短为$.getJSON("...", lpOnComplete);
标签: php jquery xss getjson long-polling