【发布时间】:2013-04-30 14:57:21
【问题描述】:
我有一个 div #notification-data,它在 $(document).ready 上填充了来自 $.post 的多个 <li></li>。
$.post 然后被称为setTimeout(poll_n,9000);,因此数据是最新的。
所以我不是每次都更新所有数据,我想检查<li></li> 是否已经存在于#notification-data 中,如果它不存在那么我想prepend() 它到#notification-data。
数据的形式为:
<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>
作为一个额外的问题,这是长轮询的正确方式吗?
这是我的代码:
function poll_n(){
$.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {
$(data).find(".li_notification").each(function () {
var li_id = $(this).attr('id');
if ($(li_id).closest('#notification-data').length) {
//do nothing
} else {
$('#notification-data').append(??not_sure_what_goes_here??); // process results here
}
});
setTimeout(poll_n,9000);
});
}
编辑 - 回答后我现在得到了这个,但它不起作用(我在控制台中什么都没有)。
success: function(data){
$(data).find(".li_notification").each(function() {
var id = $(this).attr('id'),
notification = $('#notification-data');
console.log(id);
console.log('hello');
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend('#' + id);
}
});
},
【问题讨论】:
标签: performance jquery long-polling