如何在html div中显示JSON数据

时间:2015-07-01 23:22:07

标签: javascript jquery html json

这是我的JSON字符串:

[[{"name":"Pepe Pinedo"},{"message":"something"},{"datein":"2015-07-01 11:12:34"}],[{"name":"Pepe Pinedo"},{"message":"something"},{"datein":"2015-07-01 11:14:30"}]]

这是我的js代码

$.post(url, function( data ) { //fire ajax post request
    alert("Got messages: " + data); //                         
    /*$.each(data, function(index,e){
        content += e.name + ':'+ e.message +'<br>';
        $("#chatbox").append(content);
    });*/    
});

我试图让消息看起来像这样:

enter image description here

$messages = $this->person_model->get_msg();
 foreach ($messages as $i => $valor) {
                    $fila['name']       = $valor->names;
                    $message['message'] = $valor->message;
                    $fecha['fecha']     = $valor->datein;
                    $data[] = array($fila, $message,$fecha);

            }
            echo json_encode($data); 

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

首先,您的数据结构会更有意义:

[
  { "name": "Rildo", "message": "something", "date": "2015-07-01 11:12:34" },
  { "name": "Rildo", "message": "something", "date": "2015-07-01 11:14:30" }
]

为此,您可以稍微修改一下PHP:

$messages = $this->person_model->get_msg();

foreach ($messages as $i => $valor) {
    $data[] = array(
        "name"    => $valor->names,
        "message" => $valor->message,
        "date"    => $valor->datein
    );
}

echo json_encode($data); 

然后,显示它:

$.post(url, function( data ) { // Fires an Ajax POST request

    alert("Got messages: " + data); // Alerts a String

    var messages = JSON.parse(data), // Turns the String into an Object you can manipulate
        content = '';

    $.each(messages, function(index,e){
        var time = e.date.substr(-8,5); // Extracts time from date
        content += time + ' ' + e.name + ': ' + e.message + '<br>';
    }); 

    $("#chatbox").append(content);

});

演示

&#13;
&#13;
var messages = [
        { "name": "Rildo", "message": "something", "date": "2015-07-01 11:12:34" },
        { "name": "Rildo", "message": "something", "date": "2015-07-01 11:14:30" }
    ],
    content = '';

$.each(messages, function (index, e) {
    var time = e.date.substr(-8,5);
    content += time + ' ' + e.name + ': ' + e.message + '<br>';
});

$("body").append(content);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
&#13;
&#13;
&#13;