cud*_*mer 8 php ajax jquery json getjson
我在这里做了一个噩梦,所以任何帮助都将非常感激!首先,我将解释我要做的事情:
我正在尝试使用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;
Run Code Online (Sandbox Code Playgroud)
这很好用 - 去了浏览器中的链接并验证了json响应 - 一切都很好.
然后我尝试了各种各样的jQuery东西让它工作......我发现工作的唯一方法是使用$.ajax类型POST,但只有当有等待通知时(所以返回一些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>
Run Code Online (Sandbox Code Playgroud)
由于某种原因,这只是"中止".我已尝试使用'jsonp',即使它不是CORS请求..但这也不起作用.
似乎无法随处获得!任何人都可以进入?
非常感谢
如果没有通知,getNotifications 返回什么?jQuery 期望返回 JSON 格式,但当您仅回显空字符串时,请求会失败,因为响应的格式不是 JSON。确保每次都回显 JSON 字符串。
| 归档时间: |
|
| 查看次数: |
3155 次 |
| 最近记录: |