【发布时间】:2012-07-03 01:34:46
【问题描述】:
我在这里做了一个噩梦,所以任何帮助都将不胜感激!首先,我将解释我要做什么:
我正在尝试使用 Yii 框架在我的 localhost MAMP 服务器上实现如下所述的系统:https://stackoverflow.com/a/1086448/1034392。我有一个函数可以检查数据库中是否有任何新通知 - 如果有,它会解析它们并 json 对它们进行编码。我每 5 秒在一个 while 循环中调用这个函数。
所以:转到 /user/unreadNotifications 会触发以下内容
Yii::log('test'); // to check it's getting called
$this->layout=false;
header('Content-Type: application/json');
// LONG POLLING
while (Yii::app()->user->getNotifications() == null) {
sleep(5);
}
echo Yii::app()->user->getNotifications(); // prints out json if new notification
Yii::app()->end();
return;
这很好 - 转到浏览器中的链接并验证 json 响应 - 一切都很好。
然后我尝试了各种 jQuery 的东西来让它工作......我发现工作的唯一方法是使用带有 POST 类型的 $.ajax 但只有当有等待通知时(所以返回一些 json) . $.get 或 $.post 被“中止”(显示在 firebug 中)但 URL 被调用(因为我可以看到日志文件已更新) - 奇怪。
我使用$.get 的原始设置是:
<script type="text/javascript">
function notificationPoll() {
$.get('<?php echo Yii::app()->createUrl('user/unreadNotifications') ?>','', function(result) {
$.each(result.events, function(events) {
alert('New Notification!');
});
notificationPoll();
}, 'json');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
timeout: 60 //set a global ajax timeout of a minute
});
notificationPoll();
});
</script>
这只是由于某种原因而“中止”。即使它不是 CORS 请求,我也尝试过使用 'jsonp'。但这也不起作用。
这似乎无济于事!有人可以参与吗?
非常感谢
【问题讨论】:
-
忘了提及:当我使用 $.ajax 和 POST 类型并且没有要显示的通知时,任何具有 jQuery 代码的网站页面都不会加载,直到通知通过。
-
控制台日志错误??粘贴它..
标签: php jquery ajax json getjson