繁体   English   中英

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

[英]Datatable Invalid JSON response error when my JSON is valid? PHP

我的数据表正在使用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 thats:

{
"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" }
    ]
    });

这是数据表等待的内容:

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

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

您需要这样的东西:

{
    "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']
);

当您从DataTables向服务器端脚本发出请求且processing设置为true它将发送数据。

当返回数据时,DataTables希望数据遵循这些约定。

您可以考虑这些与你的服务器端脚本(有一个很好的例子在这里 。)或选择添加数据的不同方法。 如果您可能将processing设置为false ,则可能会发现一切正常。

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM