为数据表中的第 0 行第 0 列 ajax 请求了未知参数“名称”

我无法使用 Ajax 显示数据,出现错误:


为第 0 行、第 0 列请求未知参数“名称”


HTML


<table id="datatable">

    <thead>

        <tr>

            <td>Name</td>

            <td>Surname</td>

        </tr>

    </thead>

</table>

PHP


header('Content-Type: application/json; charset=utf-8');

$columns = '{"data": [';

$columns .= '{"name": "1234567890", "surname": "test"}, ';

$columns .= '{"name": "8200469963", "surname": "amit"}';

$columns .= ']}';

die(json_encode($columns));

JavaScript


$(document).ready(function() {

    $('#datatable').DataTable({

        "responsive": true,

        "processing" : true ,

        "serverSide" : true ,

        "ajax": {

            type: 'POST',

            url: "data.php",

            dataType: 'json',

            dataSrc: ""

        },

        "columns": [

            { "data": "name" },

            { "data": "surname" }

        ]

    });

});


翻过高山走不出你
浏览 132回答 2
2回答

富国沪深

您的代码有几个问题:无效的数据表初始化设置serverSide: true和dataSrc: ""您的响应结构。PHP 脚本两次编码为 JSON。使用以下 PHP 脚本作为模板:<?phpheader('Content-Type: application/json; charset=utf-8');$data = [&nbsp; &nbsp;'data' => [&nbsp; &nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'name' => '1234567890',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'surname' => 'test'&nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'name' => '8200469963',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'surname' => 'amit'&nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp;]];echo json_encode($data);使用以下初始化选项:$(document).ready(function() {&nbsp; &nbsp; $('#datatable').DataTable({&nbsp; &nbsp; &nbsp; &nbsp; "responsive": true,&nbsp; &nbsp; &nbsp; &nbsp; "ajax": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "data.php"&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; "columns": [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "data": "name" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "data": "surname" }&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; });});

牛魔王的故事

您的 PHP 代码有两个问题:您的$columns变量是一个字符串,您试图将其编码为 JSON - 这根本不会产生您所期望的。您应该将其创建为对象,然后进行编码:$columns = ["data" => [&nbsp; &nbsp; ["name" => "1234567890", "surname" => "test"],&nbsp; &nbsp; ["name" => "8200469963", "surname" => "amit"]]];不要使用die- 这可能会对服务器端造成不良影响。使用echo来代替:echo json_encode($columns);因此,总的来说,您的 PHP 代码将是:header('Content-Type: application/json; charset=utf-8');$columns = ["data" => [&nbsp; &nbsp; ["name" => "1234567890", "surname" => "test"],&nbsp; &nbsp; ["name" => "8200469963", "surname" => "amit"]]];echo json_encode($columns);
打开App,查看更多内容
随时随地看视频慕课网APP