我的JSON有效时数据表无效的JSON响应错误? PHP

时间:2017-03-09 09:34:48

标签: php sql-server json datatables

我的数据表正在从另一个带有ajax的文件中加载它的主体,这给了我无效的JSON错误,但是当我在网络响应下检查我的开发人员工具时,我的JSON是否有效?

这是我的PHP和SQL:

<?php 
header('Content-Type: application/json');
$output = array('data' => array());
$query = "SELECT * FROM table"; 
$stmt = sqlsrv_query($sapconn2, $query);

$x = 1;

while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){

    $output['data'][] = array(
            'col_1' => $x,
            'ID' => $row['ID'],
            'QuoteID' => $row['QuoteID'],
            'CardCode' => $row['CardCode'],
            'SlpCode' => $row['SlpCode'],
            'SlpName' => $row['SlpName'],
            'BandA' => $row['BandA'],
            'NewPrice' => $row['NewPrice']
        );
    $x ++;
}

echo json_encode($output);
?>

这是我在浏览器中返回的JSON:

{
"data": [
    [1, 138, 25, "000123", "222", "test data", 222, 222],
    [2, 144, 25, "000123", "132", "test data", 465, 789],
    [3, 160, 25, "000123", "456132", "test data", 5599, 5499],
    [4, 171, 25, "000123", "789", "test data", 7897, 989],
    [5, 172, 25, "000123", "11111", "test data", 1, 11],
    [6, 182, 25, "000123", "132166", "test data", 1323, 133],
    [7, 183, 25, "000123", "135456", "test data", 1332132, 13213],
    [8, 184, 25, "000123", "1321", "test data", 5643214, 6513]
]
}

编辑:

    var testTable = $("#testTable").DataTable({
    processing: false,
    serverSide: true,
    dataType : 'json',
    ajax: "test.php",
    columns: [
        { "data": "col_1" },
        { "data": "ID" },
        { "data": "QuoteID" },
        { "data": "CardCode" },
        { "data": "SlpCode" },
        { "data": "SlpName" },
        { "data": "BandA" },
        { "data": "NewPrice" }
    ]
    });

2 个答案:

答案 0 :(得分:1)

这是数据表等待的内容:

{
    "data": [
        {
            "name": "Tiger Nixon",
            "position": "System Architect",
            "salary": "$320,800",
            "start_date": "2011/04/25",
            "office": "Edinburgh",
            "extn": "5421"
        },
        ...
    ]
}

“data”元素是一个对象数组,而是传递一个数组数组。

你需要这样的东西:

{
    "data": [
        { "id": 1, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
        { "id": 2, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
    ]
}

编辑:

$output['data'][] = array(
    'col_1' => $x,
    'col_2' => $row['ID'],
    'col_3' => $row['QuoteID'],
    'col_4' => $row['CardCode'],
    'col_5' => $row['SlpCode'],
    'col_6' => $row['SlpName'],
    'col_7' => $row['BandA'],
    'col_8' => $row['NewPrice']
);

答案 1 :(得分:1)

当您将processing设置为 true 的DataTables向服务器端脚本发出请求时,它会发送this个数据。

当它返回数据时,DataTables希望数据遵循these约定。

您可以将这些内容与服务器端脚本一起考虑(这是一个很好的示例here。)或选择其他方法来添加数据。如果您将processing设置为 false ,您可能会发现所有内容都能正常运行。

希望有所帮助。