Php &引用;非法字符串偏移量“;获取dataTable jquery插件的数组时出错

Php &引用;非法字符串偏移量“;获取dataTable jquery插件的数组时出错,php,jquery,json,ajax,datatables,Php,Jquery,Json,Ajax,Datatables,我创建了一个ajax json响应,其中将显示在我的dataTable jquery插件中。表的id为#dataTable <?php include_once('../../components/db.php'); $sql = "SELECT * FROM products WHERE status='active'"; $query = $conn->query($sql); while($data=$query->fetch_assoc()){ $image

我创建了一个ajax json响应,其中将显示在我的dataTable jquery插件中。表的id为#dataTable

<?php
include_once('../../components/db.php');

$sql = "SELECT * FROM products WHERE status='active'";
$query = $conn->query($sql);

while($data=$query->fetch_assoc()){
    $image = '<img width="50" height="40" class="rounded-circle" src="../' . $data['image'] . '">';

    $buttons = '<a href="product-update.php' . $data['id'] . '" class="btn btn-info btn-sm"><i class="fa fa-edit" aria-hidden="true"></i></a><a onclick="removeProduct(' . $data['id'] . ')" class="btn btn-danger btn-sm"><i class="fa fa-trash" aria-hidden="true"></i></a>';

    // instead of just $result[], we need to use $result[data][] in order to use it for dataTable
    $result["data"][] = array(
        $data['names'],
        $data['description'],
        $data['price'],
        $image,
        $data['availability'],
        $buttons,
    );
}

echo json_encode($result);

// console.log output would be {"data":[["Blueberry Cheesecake"," This blueberry cheesecake starts with a buttery graham cracker crust, a creamy cheesecake center, and a tangy blueberry swirl.","80.00","","Available","<\/i><\/a><\/i><\/a>"],["Fruity Split","Dessert made with a split banana, ice cream, sauce, whipped cream, nuts, and a strawberry.","50.00","","Available","<\/i><\/a><\/i><\/a>"],["Pancake","Pancake topped with blueberry and strawberry.","80.00","","Available","<\/i><\/a><\/i><\/a>"],["Steak","Steak. . . . . in which I need to output
?>
以下是dataTable插件的代码:

$(document).ready(function() {
    var productTable = $("#dataTable").DataTable({
        "ajax": "../api/ajax/getProduct.php",
        "order": [[ 1, "desc" ]]
    });
});
下面是getProduct.php

<?php
include_once('../../components/db.php');

$sqlb = "SELECT * FROM products WHERE status='active'";
$resultb = $conn->query($sqlb);
$data = $resultb->fetch_assoc();

$result = array();

foreach ($data as $key => $value) {
    $image = '<img width="50" height="40" class="rounded-circle" src="../' . $value['image'] . '; ?>">';

    $buttons = '<a href="product-update.php' . $value["id"] . '" class="btn btn-info btn-sm"><i class="fa fa-edit" aria-hidden="true"></i></a><a onclick="removeProduct(' . $value["id"] . ')" class="btn btn-danger btn-sm"><i class="fa fa-trash" aria-hidden="true"></i></a>';

    $result[$key] = array(
        $value["description"],
        $value["price"],
        $image,
        $value["availability"],
        $buttons,
    );
}// /foreach

echo json_encode($result);
?>

这是我在加载页面时从dataTable本身得到的弹出错误

DataTables warning: table id=dataTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
看起来这里真正的问题是编码数据本身是错误的。由于此错误,我无法将数据显示到数据表本身。

基于
var\u dump($data)结果:

 array(9) {
  ["id"]=>
  string(1) "2"
  ["names"]=>
  string(12) "Fruity Split"
  ["price"]=>
  string(5) "50.00"
  ["qty"]=>
  string(1) "1"
  ["image"]=>
  string(26) "images/products/menu-2.jpg"
  ["description"]=>
  string(90) "Dessert made with a split banana, ice cream, sauce, whipped cream, nuts, and a strawberry."
  ["category"]=>
  string(7) "dessert"
  ["availability"]=>
  string(9) "Available"
  ["status"]=>
  string(6) "active"
}
导致此错误的原因:

警告:字符串偏移量非法

这是因为您正在循环1行

改为将代码更改为:

<?php
include_once('../../components/db.php');

$sqlb = "SELECT * FROM products WHERE status='active'";
$resultb = $conn->query($sqlb);

// This just return single row
// $data = $resultb->fetch_assoc();

$result = array();

//Use while instead of foreach
while ($value =  $resultb->fetch_assoc()) {
    $image = '<img width="50" height="40" class="rounded-circle" src="../' . $value['image'] . '; ?>">';

    $buttons = '<a href="product-update.php' . $value["id"] . '" class="btn btn-info btn-sm"><i class="fa fa-edit" aria-hidden="true"></i></a><a onclick="removeProduct(' . $value["id"] . ')" class="btn btn-danger btn-sm"><i class="fa fa-trash" aria-hidden="true"></i></a>';

    // Add Keys For DataTable column
    $result[] = array(
        'description' => $value["description"],
        'price' => $value["price"],
        'image' => $image,
        'availability' => $value["availability"],
        'buttons' => $buttons,
    );
}

echo json_encode($result);
?>

根据@Bluetree的回答,为dataTable添加键是不必要的

正确的方法是,编码的数据数组应该首先在数组中输入数据字符串“data”,因为我们只需要遵循dataTable所需的格式

<?php
include_once('../../components/db.php');

$sql = "SELECT * FROM products WHERE status='active'";
$query = $conn->query($sql);

while($data=$query->fetch_assoc()){
    $image = '<img width="50" height="40" class="rounded-circle" src="../' . $data['image'] . '">';

    $buttons = '<a href="product-update.php' . $data['id'] . '" class="btn btn-info btn-sm"><i class="fa fa-edit" aria-hidden="true"></i></a><a onclick="removeProduct(' . $data['id'] . ')" class="btn btn-danger btn-sm"><i class="fa fa-trash" aria-hidden="true"></i></a>';

    // instead of just $result[], we need to use $result[data][] in order to use it for dataTable
    $result["data"][] = array(
        $data['names'],
        $data['description'],
        $data['price'],
        $image,
        $data['availability'],
        $buttons,
    );
}

echo json_encode($result);

// console.log output would be {"data":[["Blueberry Cheesecake"," This blueberry cheesecake starts with a buttery graham cracker crust, a creamy cheesecake center, and a tangy blueberry swirl.","80.00","","Available","<\/i><\/a><\/i><\/a>"],["Fruity Split","Dessert made with a split banana, ice cream, sauce, whipped cream, nuts, and a strawberry.","50.00","","Available","<\/i><\/a><\/i><\/a>"],["Pancake","Pancake topped with blueberry and strawberry.","80.00","","Available","<\/i><\/a><\/i><\/a>"],["Steak","Steak. . . . . in which I need to output
?>
将是这样编码的简写方式:

$('#example').dataTable( {
  "ajax": {
    "url": "data.json",
    "data": {
        "user_id": 451
    }
  }
} );

因为ajax的第一个示例格式本身已经有了url和数据。url中的返回值是数据本身,ajax的url是url本身。因此,我们需要在数组的编码结果中的返回值中包含一个“数据”。

删除$buttons之后$result数组中的最后一个逗号,如果这不能解决问题,请尝试回显测试字符串,看看得到了什么。echo json_编码(“测试”);另外,在getProduct.php页面的顶部添加标题(“内容类型:application/json;charset=utf-8”);就在$include_once(“……之后,尝试
var_dump($data);die()
之前,在
foreach
之前,将结果发布到这里。@Icewine我尝试过你的方法。我添加了头并添加了json_编码(“test”)。我使用ajax响应测试了它的输出,但它没有输出“test”“在街上console@Bluetree删除json_编码(“test”)并将$result放回那里,但保留前面的头。然后在代码中紧跟$(document).ready(function(){和var productTable之前…添加一个新的ajax请求以测试您得到的响应。尝试以下操作:$.ajax({type:'post',url:../api/ajax/getProduct.php),成功:函数(数据){console.log(“成功”);console.log(数据);},错误:函数(e){console.log(“错误”);console.log(e);});第18行有错误$key未定义。删除$key后,输出仅为1行,数据库输出上的最后一行数据应为database@LexCabrera我删除了
$key
。请再试一次。@LexCabrera这将显示产品中的所有活动状态。如果只有1个,请检查产品表
active
行。此处有多个“active”行。您可以
var\u dump($result);die();
while
循环之后。将其置于
while
循环之外。
$('#example').dataTable( {
  "ajax": {
    "url": "data.json",
    "data": {
        "user_id": 451
    }
  }
} );