dtxs9017 2013-06-27 13:48
浏览 20
已采纳

通过PHP从JSON获取新项目

I need to load new messages which weren't loaded yet and add them by $.append to a div, but I dont know how.
The best way would be to check it by the time. var chatdata = null;

$.ajax({
    type: "GET",
    data: {id: id},
    url: "/chatbin/receive-bin.php",
    dataType: "json",
    cache: false,
    async: true,
    contentType: "application/json",
    success: function(data) {
        chatdata = "";
        $('#chattext').html('');
        $.each(data.messages, function(i,dat){
            chatdata += "<div class='message'><img class='chatuserimg' src='/assets/userpics/" + dat.id + "_64.png'><span class='userdname'>" + dat.dname + "<span class='time'>" + dat.time + "</span></span><div class='message_text'>" + dat.message + "</div></div>
";
        });

        gotoBottom();
        $('#chattext').append(chatdata);
        gotoBottom();

        c_id = id;
        autofocus();

        setInterval(checkNewmsg, 1000);
    },
    error: function(xhr, status, error) {
        alert('There was an error while sending the request, please try again later.');
   }
});

JSON FILE:

{"messages": [
{"dname":"Person1", "id":"1", "message":"Hi", "time":"25.06.2013, 14:49"}, 
{"dname":"Person2", "id":"2", "message":"Cheers", "time":"25.06.2013, 14:50"}
]}
  • 写回答

1条回答 默认 最新

  • duanmo5724 2013-06-27 14:08
    关注

    If time is unique identifier of the message then play with time

    $.ajax({
        type: "GET",
        data: {id: id},
        url: "/chatbin/receive-bin.php",
        dataType: "json",
        cache: false,
        async: true,
        contentType: "application/json",
        success: function(data) {
            chatdata = "";
            $('#chattext').html('');
            $.each(data.messages, function(i,dat){
    
              //play with class here -- if time is unique identifier of the message
              var class = date.time.replace(/\./g,"-").replace(/\:/g,"-").replace(/\,\s/g,"-");
    
               if(!$('.message').hasClass(class))
               {
                 chatdata += "<div class='message "+class+"' ><img class='chatuserimg' src='/assets/userpics/" + dat.id + "_64.png'><span class='userdname'>" + dat.dname + "<span class='time'>" + dat.time + "</span></span><div class='message_text'>" + dat.message + "</div></div>
    ";
               }
            });
    
                gotoBottom();
                $('#chattext').append(chatdata);
                gotoBottom();
    
                c_id = id;
                autofocus();
    
                setInterval(checkNewmsg, 1000);
        },
        error: function(xhr, status, error) {
            alert('There was an error while sending the request, please try again later.');
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?