通过AJax调用返回格式Json并将其分配给javascript变量

时间:2016-05-01 22:55:22

标签: javascript jquery json ajax

我有使用ajax调用从服务器返回此脚本的脚本

//ajax call
var comment_frm = $('#comment_form');
                comment_frm.submit(function (ev) {
                    $.ajax({
                        type: comment_frm.attr('method'),
                        url: comment_frm.attr('action'),
                        data: comment_frm.serialize(),
                        success: function (data) {
                            if (data == 1){
                                $("#success_message").show();
                                $('#comment_form').trigger("reset");
                            }
                        },
                        error: function (jXHR, textStatus, errorThrown) {
                            alert(errorThrown);
                        }
                    });
                    //prevent the page from loading
                    ev.preventDefault();
                });

[{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]

我想将其格式化为这样,并将json结果分配给javascript变量

var comment_array = {"Comments": [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"coment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]}



 //php code
    $operation = $_POST['operation'];
if($operation == 'add_comment'){
    $name = $_POST['name'];
    $comment = $_POST['comment'];
    $blog_id = $_POST['blog_id'];
    $comment_status = 1;
    if ($me->add_comment($name, $comment, $blog_id)){
        //get the comment
        $comment_array = $me-> fetch_moderated_comment($blog_id);
        echo json_encode($comment_array);
    }else{echo 10;}
}

我也很想知道如何通过电话阅读...有人可以帮助我

3 个答案:

答案 0 :(得分:2)

Working Example

您可以指定一个变量来保存新的“评论”数组,然后按下它:

thing.getThing()

答案 1 :(得分:1)

echo json_encode(['Comments' => $comment_array]);

答案 2 :(得分:1)

如果我理解正确,只需将结果包装在对象文字中:

cucumber --tags @wip