dongxi7722 2014-07-03 19:36 采纳率: 0%
浏览 54
已采纳

HTML标记中的JSON和CodeIgniter

I am trying to create a private chatroom using CodeIgniter and JSON. I would like the returned JSON data to be put in a list like <ul><li>messageinJSON</li></ul>. This will permit me to style the users chat messages. I have tried different approaches I have seen on SO but there is no example quite like my need.

My Controller:

         public function get_chats() {
            $this->load->model('pchat_model');
            $this->pchat_model->create_table();
            echo json_encode($this->pchat_model->get_chat_after($_REQUEST["time"]));
            return;
         }

My JS:

 var addDataToReceived = function(arrayOfData) {
        arrayOfData.forEach(function(data) {
            $("#received").val($("#received").val() + "
" + data[0]);
        });
    }



     var getNewChats = function() {
            $.getJSON("pchat/get_chats?time=" + time, function(data) {
                addDataToReceived(data);
                setTimeout(function() {
                    $('#received').animate({scrollTop:$('#received')[0].scrollHeight}, 3000);
                }, 0);
                time = data[data.length - 1][1];
            });
        }

UPDATE: getNewChats called in (document).ready function

$(document).ready(function() {
        $("form").submit(function(evt) {
            evt.preventDefault();
            var data = $("#text").val();
            $("#text").val('');
            sendChat(data, function() {
                alert("dane");
            });
        });
        setInterval(function() {
            getNewChats(0);
        }, 5500);
    });
  • 写回答

1条回答 默认 最新

  • doubeng9567 2014-07-03 21:14
    关注

    In your JS getNewChats function call should look like this

    function getNewChats(time){
        $.get("pchat/get_chats?time=" + time, function(data){
            console.log(data); //Dumping your JSON data out into browser console window. You can replace it with your unordered list here.
        }, 'json');
    }
    

    So in the JS code example above all we are doing is asking your PHP script for data. You'll notice that in the $.get function call I have a 'json' at the end of it. That's to tell jQuery that the GET command expects to see a JSON data return.

    From there your JSON data is dumped out into your browser console.

    Update:

    Okay to be more clear I added a JSFiddle to show you an example how it will work based off your document.ready function call. With that code you can stylize it however you like by adding the appropriate classes names to the un-ordered list. You can have your functions wrapped in a var or without. That's just up to your own coding style.

    http://jsfiddle.net/JqXea/

    Do note that this example is only displaying random numbers.

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

报告相同问题?