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


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() {
            echo json_encode($this->pchat_model->get_chat_after($_REQUEST["time"]));

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) {
                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) {
            var data = $("#text").val();
            sendChat(data, function() {
        setInterval(function() {
        }, 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.


    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.

    Do note that this example is only displaying random numbers.

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



  • ¥50 Java编程实现多功能计算器
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 maccms影视模板 制作影视网站失败 求
  • ¥15 stm32按键设置闹钟数进退位不正常
  • ¥15 自己写的测试驱动程序无法启动
  • ¥15 三电平逆变器中点电位平衡问题
  • ¥20 这怎么写啊 java课设
  • ¥15 用C语言完成一个复杂的游戏
  • ¥15 如何批量更改很多个文件夹里的文件名中包含文件夹名?
  • ¥50 MTK手机模拟HID鼠标出现卡顿