首页 > 解决方案 > 无法使用 ajax 源填充数据表

问题描述

我无法使用 ajax 数据源填充数据表。我正在使用 Codeigniter 版本 3 和 WAMP v 3.2.0。查看代码:

<table class="table table-striped table-bordered table-hover" cellspacing="0" id="farmer_data_table">
   <thead>
         <tr>
            <th>First Name</th>
            <th>Gender</th>
             <th>Phone No.</th>
             <th>City/Town</th>
             <th>PIN</th>
             <th>State</th>
         </tr>
   </thead>
</table>

<script type="text/javascript">
    $(document).ready(function () {
        $('#farmer_data_table').DataTable( {
            "ajax": "<?=site_url();?>nautics/farmers/fetch_farmer_data/",
            "columns": [
                { "data": "first_name" },
                { "data": "gender" },
                { "data": "phone_number" },
                { "data": "city_town" },
                { "data": "pin_code" },
                { "data": "state" }
            ]
        } );
    });

控制器代码:

public function fetch_farmer_data()
{
    $url="http://<IP Address>/api/v1/form-data/all-record";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'x-access-token: ' . $this->session->userdata('access_token')
    ));

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response,true);
    //var_dump($result);
}

var_dump($result) 将数据显示为:

array (size=1)
  'data' => 
    array (size=6)
      0 => 
        array (size=28)
          'active' => boolean true
          'address' => string 'Golghat,-' (length=9)
          'age' => int 27
          'alt_phone_number' => string '' (length=0)
          .................................more key-value pairs
      1 => 
        array (size=28)
          'active' => boolean true
          'address' => string 'Golaghat,-' (length=10)
          'age' => int 27
          'alt_phone_number' => string '' (length=0)
        .................................more key-value pairs

错误信息是:

DataTables warning: table id=farmer_data_table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

谁能告诉我我的 json 数据格式是否不正确,或者填充数据表的整个代码是否错误。提前致谢。

标签: phpajaxcodeigniterdatatable

解决方案


你的控制器没有返回任何东西。

您正在$result = json_decode($response,true);创建 JSON,但控制器不会将其提供给请求站点。

在上面提到的行之后你应该有类似的东西:

return $this->output
            ->set_content_type('application/json')
            ->set_output($result);

编辑:

该行$result = json_decode($response,true);也是错误的,您有一个数组,您希望将其转换为 JSON。所以你必须使用它json_encode来代替响应。


推荐阅读