簡體   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