dte8665 2017-03-09 07:40
浏览 32
已采纳

当新密钥在json中时,PHP ajax添加新的div

First i want to thank you for reading this :).

Im creating a Live chat with PHP and jQuery. Yeah iknow what you'r thinking right now. USE SOCKET.IO. Iknow, and i want to. But first i want to create one with Ajax. So if you are gonna say use websockets or node.js or something it doesnt help me. I just want to fix this.

So my problem.

The chat data will be parsed in a json array on a file.

[{"id":"1","user_id":"2","user_clr":"red","message":"Test bericht","timestamp":"2017-03-09 16:04:34","username":"Vienna"},{"id":"2","user_id":"1","user_clr":"blue","message":"Test berciht 2","timestamp":"2017-03-09 16:04:32","username":"Chris"},{"id":"3","user_id":"2","user_clr":"red","message":"tst bericht 4","timestamp":"2017-03-09 16:04:35","username":"Vienna"},{"id":"4","user_id":"2","user_clr":"red","message":"test bericht 3","timestamp":"2017-03-09 16:04:36","username":"Vienna"},{"id":"5","user_id":null,"user_clr":"sda","message":null,"timestamp":null,"username":null},{"id":"6","user_id":"1","user_clr":"blue","message":"Test","timestamp":null,"username":"Chris"},{"id":"7","user_id":null,"user_clr":null,"message":null,"timestamp":null,"username":null},{"id":"8","user_id":null,"user_clr":null,"message":"TEST","timestamp":null,"username":"TEST"}]

Yes it is a valid JSON.

there are some nulls in it but it doesnt matter.

Im using at this moment this jQuery:

function loadChats(){
$.getJSON('/d.php', function(data) {
    console.log(data.length + " keys loaded");
    var strVar="";
    $( "#view_ajax" ).empty();
    $.each(data, function(index) {
       strVar += "<div class=\"messenger-message-container\" style=\"color:white;\">";
    strVar += "                              ";
    strVar += "                                <div class=\"messages\">";
    strVar += "                                    <ul>";
    strVar += "                                        <li>";
    strVar += "";
    strVar += "                                            <div class=\"message\"><font color=\"black\">";
    strVar +=                                              "<\/font>";
    strVar += "                                               ";
    strVar += "                                                <div style=\"background-color:" + data[index].user_clr + ";\">";
    strVar +=                                                   data[index].username + ": " + data[index].message;
    strVar += "                                                <\/div>";
    strVar += "                                            <\/div>";
    strVar += "                                        <\/li>";
    strVar += "                                          <div class=\"time-ago\">1:26<\/div>";
    strVar += "                                    <\/ul>";
    strVar += "                                <\/div>";
    strVar += "                                ";
    strVar += "                            <\/div>";

    });
    $('#view_ajax').append(strVar);

});
setTimeout("loadChats()", 1000);
}

 loadChats();

Now it is refreshing the whole div. It emptys the html and put the html again into the strVar, so new data will be included now either.

But what i really want is to load the chat when you open the chat page and then only check if theire is a new row in the database. If so, put a new div on the output page. So the olders message wouldt be loaded again.

How can i realize this?

I tried to read other ajax tutorials about data, but i cant find the right one which is cleared what i want.

----- Added PHP code for answer from: Guillaume STLR

<?php
require_once './core/init.php';
$toxDB = toxDB::getInstance();
$toxData = $toxDB->getAll('chats', 20);
print_r(json_encode($toxData->results()));

this query is running when running this function

object(PDOStatement)[4]
public 'queryString' => string 'SELECT * FROM chats LIMIT 20' (length=28)

and is printing the JSON which i mention above.

展开全部

  • 写回答

1条回答 默认 最新

  • dongpao5261 2017-03-09 07:45
    关注

    You can try to store locally which ids are already rendered :

    function loadChats(){
        $.getJSON('/d.php', function(data) {
            console.log(data.length + " keys loaded");
            var strVar="";
            $.each(data, function(index) {
                if(cacheId.indexOf(data[index].id) === -1) {
                    //Store to cache
                    cacheId.push(data[index].id);
                    strVar += "<div class=\"messenger-message-container\" style=\"color:white;\">";
                    strVar += "                              ";
                    strVar += "                                <div class=\"messages\">";
                    strVar += "                                    <ul>";
                    strVar += "                                        <li>";
                    strVar += "";
                    strVar += "                                            <div class=\"message\"><font color=\"black\">";
                    strVar +=                                              "<\/font>";
                    strVar += "                                               ";
                    strVar += "                                                <div style=\"background-color:" + data[index].user_clr + ";\">";
                    strVar +=                                                   data[index].username + ": " + data[index].message;
                    strVar += "                                                <\/div>";
                    strVar += "                                            <\/div>";
                    strVar += "                                        <\/li>";
                    strVar += "                                          <div class=\"time-ago\">1:26<\/div>";
                    strVar += "                                    <\/ul>";
                    strVar += "                                <\/div>";
                    strVar += "                                ";
                    strVar += "                            <\/div>";
                }
            });
            $('#view_ajax').append(strVar);
    
        setTimeout("loadChats()", 1000);
        });
    }
    //Add caching
    var cacheId = [];
    loadChats();
    

    You can also filter your datas with backend by sending to server the last chat id value and filtering with this. Like this :

    PHP :

    $lastId = isset($_GET['last_id']) ? $_GET['last_id'] : null;
    require_once './core/init.php';
    $toxDB = toxDB::getInstance();
    
    if($lastId) {
        //Don't know how to filter with your model, but you get it.
        $toxData = $toxDB->getAllBy('chats', 'WHERE ID > :ID', ['ID' => $lastId], 20);
    }else {
        $toxData = $toxDB->getAll('chats', 20);
    }
    
    print_r(json_encode($toxData->results()));
    

    Javascript :

     function loadChats() {
        $.getJSON('/d.php?last_id=' + lastId, function(data) {
            console.log(data.length + " keys loaded");
            var strVar="";
            $.each(data, function(index) {
                //Set last chat id
                lastId = data[index].id;
                strVar += "<div class=\"messenger-message-container\" style=\"color:white;\">";
                strVar += "                              ";
                strVar += "                                <div class=\"messages\">";
                strVar += "                                    <ul>";
                strVar += "                                        <li>";
                strVar += "";
                strVar += "                                            <div class=\"message\"><font color=\"black\">";
                strVar +=                                              "<\/font>";
                strVar += "                                               ";
                strVar += "                                                <div style=\"background-color:" + data[index].user_clr + ";\">";
                strVar +=                                                   data[index].username + ": " + data[index].message;
                strVar += "                                                <\/div>";
                strVar += "                                            <\/div>";
                strVar += "                                        <\/li>";
                strVar += "                                          <div class=\"time-ago\">1:26<\/div>";
                strVar += "                                    <\/ul>";
                strVar += "                                <\/div>";
                strVar += "                                ";
                strVar += "                            <\/div>";
            });
            $('#view_ajax').append(strVar);
    
        });
    
        setTimeout("loadChats()", 1000);
    }
    
    var lastId = null;
    loadChats();
    

    If you had to choose : Filtering is better. With your solution, every second you send unecessary (and potentially big) JSON to every clients connected to your page, even if the chat conversations are already rendered. With filtering you're saving bandwith and database operations by adding a WHERE filter.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 torch框架下的强化学习DQN训练奖励值浮动过低,希望指导如何调整
  • ¥35 西门子博图v16安装密钥提示CryptAcquireContext MS_DEF_PROV Error of containger opening
  • ¥15 mes系统扫码追溯功能
  • ¥40 selenium访问信用中国
  • ¥20 在搭建fabric网络过程中遇到“无法使用新的生命周期”的报错
  • ¥15 Python中关于代码运行报错的问题
  • ¥500 python 的API,有酬谢
  • ¥15 软件冲突问题,软件残留问题
  • ¥30 有没有人会写hLDA,有偿求写,我有一个文档,想通过hLDA得出这个文档的层次主题,有偿有偿!
  • ¥50 有没有人会写hLDA,有偿求写,我有一个文档,想通过hLDA得出这个文档的层次主题,有偿有偿!
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部