【问题标题】:Polling jQuery ajax for each. Check if element does not exist, if so prepend to div轮询每个 jQuery ajax。检查元素是否不存在,如果存在则添加到 div
【发布时间】: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


    【解决方案1】:

    你可以试试这个:

    function poll_n() {
    $.ajax({
        type: 'POST',
        url: 'your url',
        success: function(data){
            var notification = $('#notification-data');
            $.each($(data), function(){
                var id = this.id;
                if (notification.find('#' + id).length === 0) {
                    // notification doesn't exists yet then lets prepend it
                    notification.prepend(this);
                }
            });
        },
        complete: function(jqXHR, status) {
            if (status === 'success') {
                setTimeout(poll_n, 9000);
            }
        }
    });
    }
    

    请求完成后,您必须再次致电poll_n()

    【讨论】:

    • 它只是将它们全部追加
    • 即使id 相同也要追加?
    • 是的,我有 6 个
    • 用于测试,每个都有单独的 id。它只是每次都附加所有 6 个,所以我最终得到 12、18、24 等
  • 我编辑了上面的代码。我忘了把# 放在find(id) 中。应该是find('#' + id)
  • ;) 太棒了,似乎有效。这是长轮询的正确方式吗?
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签