【问题标题】:PHP with DataTables gives an Invalid JSON response due to quotes由于引号,带有 DataTables 的 PHP 给出了无效的 JSON 响应
【发布时间】:2018-06-12 02:06:54
【问题描述】:

我在从数据库中提取数据并通过 DataTables 显示时遇到问题。我发现我的大部分数据都有单引号和双引号以及其他特殊字符。我尝试了 PHP 中的每个转义函数,但没有成功。 addslashes 仅检索 40,000 条数据中的 59 条数据。到目前为止,我有这个代码:

PHP:

$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");

$table = '';

while($row = mysqli_fetch_array($query)) {


    $table.= '{
        "allotment_code":"'.$row['allotment_code'].'",
        "activity":"'.$row['activity'].'",
        "category_name":"'.addslashes($row['category_name']).'",
        "description":"'.addslashes($row['description']).'"
    },';
}


$table = substr($table,0, strlen($table) - 1);

echo '{"data":['.$table.']}';


**jQuery data tables:**

    $(function() {

        $('#dataTables-example').DataTable( {
            "bLengthChange": false,
            "pageLength": 50,
            "bDeferRender": true,
            "bProcessing": true,
            "sPaginationType": "full_numbers",
            "ajax": base_url('ajax/ajaxGetBOM.php'),
            "columns":[
                {mData: "allotment_code"},
                {mData: "activity"},
                {mData: "category_name"},
                {mData: "description"}
            ],
            contentType: 'application/json',
            dataType: 'json'
        });
    })

    function base_url(path) {

        var url = 'https://192.168.3.254/'+path;
        return url;
    }

错误是这样的:

【问题讨论】:

  • 我猜您的数据没有以有效的 JSON 格式发送到表中?过去,我使用过 PHP 的 json_encode,它似乎可以很好地处理任何问题。也许试一试,而不是从查询中构建自己的 JSON 字符串?
  • 我会试试的。感谢您的回复。
  • addslashes() 是一个 PHP 函数,一般来说几乎没有什么实用性,但它特别不适合构建 JSON。

标签: php jquery mysql json datatables


【解决方案1】:

使用json_encode() 函数以使用 JSON 格式正确编码您的响应。

$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");

$data = array();   
while($row = mysqli_fetch_array($query)) {
   $data[] = array(
      "allotment_code" => $row["allotment_code"],
      "activity" => $row["activity"],
      "category_name" => $row["category_name"],
      "description" => $row["description"]
   );
}

header("Content-type: application/json");
echo json_encode(array("data" => $data));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2018-10-31
    • 2015-04-20
    • 2014-11-04
    相关资源
    最近更新 更多