Таблица данных обработки на стороне сервера Jquery с одним дополнительным столбцом в качестве ссылки с идентификатором строки? - PullRequest
0 голосов
/ 30 ноября 2018

Я делаю нумерацию на стороне сервера с таблицей данных jquery и php на стороне сервера.

Below is the image of my server side data table

Мне нужен дополнительный заголовок столбцакак скачать с данными в виде ссылки с соответствующим его идентификатором.например: <a href="abc.com/id">Download</a> .

Ниже приведен мой HTML-код

<table id="employee_grid" class="display" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>Empid</th>
                <th>Name</th>
                <th>Salary</th>
                <th>Age</th>
            </tr>
        </thead>


    </table>

Мой JS

$('#employee_grid').DataTable({
        "bProcessing": true,
         "serverSide": true,
         "ajax":{
            url :"response.php", // json datasource
            type: "post",  // type of method  ,GET/POST/DELETE
            error: function(){
              $("#employee_grid_processing").css("display","none");
            }
          }
        });   
});

Php

<?php
    //include connection file 
    include_once("connection.php");

    // initilize all variable
    $params = $columns = $totalRecords = $data = array();

    $params = $_REQUEST;



    //define index of column
    $columns = array( 
        0 =>'id',
        1 =>'employee_name', 
        2 => 'employee_salary',
        3 => 'employee_age'
    );

    $where = $sqlTot = $sqlRec = "";

    // check search value exist
    if( !empty($params['search']['value']) ) {   
        $where .=" WHERE ";
        $where .=" ( employee_name LIKE '".$params['search']['value']."%' ";    
        $where .=" OR employee_salary LIKE '".$params['search']['value']."%' ";

        $where .=" OR employee_age LIKE '".$params['search']['value']."%' )";
    }

    // getting total number records without any search
    $sql = "SELECT * FROM `employee` ";
    $sqlTot .= $sql;
    $sqlRec .= $sql;
    //concatenate search sql if value exist
    if(isset($where) && $where != '') {

        $sqlTot .= $where;
        $sqlRec .= $where;
    }


    $sqlRec .=  " ORDER BY ". $columns[$params['order'][0]['column']]."   ".$params['order'][0]['dir']."  LIMIT ".$params['start']." ,".$params['length']." ";

    $queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));


    $totalRecords = mysqli_num_rows($queryTot);

    $queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");

    //iterate on results row and create new index array of data
    while( $row = mysqli_fetch_row($queryRecords) ) { 
        $data[] = $row;
    }   

    $json_data = array(
            "draw"            => intval( $params['draw'] ),   
            "recordsTotal"    => intval( $totalRecords ),  
            "recordsFiltered" => intval($totalRecords),
            "data"            => $data   // total data array
            );

    echo json_encode($json_data);  // send data as json format
?>

Я пыталсяиспользование визуализации столбцов и несколько других вещей, но не в состоянии разобрать.Любая помощь?

1 Ответ

0 голосов
/ 30 ноября 2018

Для этого вам необходимо использовать опции columnDefs и column.render.

https://datatables.net/reference/option/columnDefs

https://datatables.net/examples/advanced_init/column_render.html

Вы должны иметь возможность визуализировать свои строкидобавив это к вашей инициализации DataTable:

"columnDefs": [
 {

  "render": function ( data, type, row ) {
    let rowID = row[0];
    return `<a href="abc.com/${ rowID }">Download</a>`
   },
   "targets": 4

 }
]

Вам также необходимо добавить новый столбец в html

<table id="employee_grid" class="display" width="100%" cellspacing="0">
 <thead>
  <tr>
   <th>Empid</th>
   <th>Name</th>
   <th>Salary</th>
   <th>Age</th>
   <th>Download</th>
  </tr>
 </thead>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...