【问题标题】:Why JSON returns double rows for each row within resultSet为什么 JSON 为 resultSet 中的每一行返回双行
【发布时间】:2020-02-09 15:46:28
【问题描述】:

我有以下 php 代码:

 echo(json_encode(array('msg'=>'7','result'=>$list)));

它使用ajax返回以下json:

 msg    7
 result […]
        0   {…}
        0   2
        1   Family, Release
        2   test 2 v/s test 3
        3   this is the test for judgment file 2
        4   null
        5   2019-10-10 10:10 PM
        6   1
        7   null
        8   1
        sno 2
        keywords    Family, Release
        case_title  test 2 v/s test 3
        law this is the test for judgment file 2
        judgment_file   null
        added_on    2019-10-10 10:10 PM
        added_by    1
        user_ip null
        is_confirmed    1
        1   {…}
        0   3
        1   Family
        2   Test 3 V/S Test 4
        3   this is tthird record
        4   null
        5   2019-10-10 10:10 PM
        6   1
        7   null
        8   1
        sno 3
        keywords    Family
        case_title  Test 3 V/S Test 4
        law this is tthird record
        judgment_file   null
        added_on    2019-10-10 10:10 PM
        added_by    1
        user_ip null
        is_confirmed    1

问题 1:它返回单行结果两次,即使用 0,1,...8 而使用表字段名称,即 sno = 2 个关键字 = xxx

我需要为每一行获取单个结果。

问题2:如何使用JavaScript/jQuery从json中获取所有字段?

【问题讨论】:

  • $list 已经是 json 了吗?另外,您能否格式化输出更多。使用console.log("%j", jsonObj);console.log(JSON.stringify(data)) 在控制台打印格式化数据。

标签: php jquery json


【解决方案1】:

$list 本身包含重复项,这就是 PHP 返回的内容。您必须从 php 中的 $list 数组/对象/对象数组中消除重复项。

查看这个工作示例:

index.php

<button class="button">Get JSON response</button>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
    $('.button').on('click', function (e) {
        $.ajax({
            url: "test.php",
            method: "POST",
            dataType: "json"
        }).done(function (msg) {
            console.log(msg);
        }).fail(function (jqXHR, textStatus) {
            console.log('Request failed: ' + textStatus);
        });
    });
</script>

ajax.php

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $list = new stdClass();
    for ($i = 0; $i < 10; $i++) {
        $list->{'name' . $i} = 'Value ' . $i;
    }

    header('Content-Type: application/json');
    echo(json_encode(array('msg' => '7', 'result' => $list)));
}
?>

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2016-04-24
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多