AJAX逐行读取JSON文件

时间:2014-08-03 02:09:13

标签: javascript jquery html ajax json

我一直在玩AJAX,我试图逐行阅读PHP响应并将其解析为JSON。有没有办法将整个事物解析为JSON数组?

PHP中的服务器端:

<?php
        echo json_encode(array(
                "nick" => "mod",
                "id" => "admin",
                "msg" => "hi"
        ));
    echo json_encode(array(
                "nick" => "other",
                "id" => "1",
                "msg" => "hello"
        ));
?>

在JavaScript中:

 $.ajax({
        type: 'get',
        url: 'getInfo.php',
        dataType: 'json',
        success: function (data) {
                $('.div').html('');
                //data.forEach(function (entry) {
                        var name = data.nick;
                        var id = data.id;
                        var msg = data.msg;
                        var html = $('.chat').html();
                        html += "<h5>" + name + " (" + id + ")</h5>";
                        $('.div').html(html);
                //});
        }
});

2 个答案:

答案 0 :(得分:0)

我认为你应该改变你的PHP代码。 正如您在评论中所说,您的输出为{name:"item one", id:"0"} {name:"item two", id:"1"},但您应该获得此[{name:"item one", id:"0"},{name:"item two", id:"1"}]

我认为以下代码更好:

<?php
    echo json_encode(array(
        array(
            "nick" => "mod",
            "id" => "admin",
            "msg" => "hi")
        ),array(
            "nick" => "other",
            "id" => "1",
            "msg" => "hello"
        )
    );
?>

答案 1 :(得分:0)

使用JSON_PRETTY_PRINT的{​​{1}}选项,如下所示:

json_encode