使用服务器端处理对数据表进行分页

时间:2021-06-25 18:01:46

标签: jquery ajax datatables

我正在使用 ajax 查询我的数据库并带回数据的 json 对象。我想使用 DataTables 对数据进行分页。我无法让 DataTables 识别我的帖子变量(名为“代码”)并以表格格式返回任何数据。有人可以帮忙吗?

html:

<label for="medProcDataList" class="form-label">Medical Procedures with hospital codes</label>
    
    <select class="form-select" id="medProcDataList">
      <option value="">Select</option>
      <!-- this is populated with a different ajax call -->
    </select>
</form>

<table id="results"></table>

jquery

var $selectedValue = $(this).val();
var arrSelVal = $selectedValue.split(":");
$code = arrSelVal[0]; //get hospital code

$('#results').DataTable( { //returns nothing; does not recognize my code variable
        "processing": true,
        "serverSide": true,
        data: {code: $code },
        "ajax": "php/getDataForCode.php",
        columns: [
                { title: "Hospital", data: "hospital_name" },
                { title: "Description", data: "raw_description" },
                { title: "Insurer", data: "full_payer_name" },
                { title: "Insurer type", data: "play_type"},
                { title: "You Pay", data: "price" }
        ]
    } );

php

$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
        printf("Connect failed: %s", mysqli_connect_error());
        exit;
}
mysqli_set_charset($db, 'utf8'); //important! or it won't echo the array

    if( $_POST) {
        $code = mysqli_real_escape_string($db, $_POST['code']);
        $data = array();
        $q = "SELECT hospital_name, raw_description, full_payer_name, plan_type, format([price], 'N0') FROM `hospital_transparency_data` where procedure_codes = '" . $code . "' order by hospital_name, full_payer_name";
        $result = $db->query($q);
        while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            //Add this row to the reply
            $data[] = $row;
        }
        
        
        $db->close();
        echo json_encode($data);
    
    } //if POST

我这样做对吗? DataTables 无法识别我的数据变量并引发错误:

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

0 个答案:

没有答案