【问题标题】:Clickable Data Table Row可点击的数据表行
【发布时间】:2017-12-22 22:43:06
【问题描述】:

我有一个从 MySQL 数据库中获取数据的数据表。在我的数据库中,我有一个名为“位置”的列,它是指向某个音频文件的链接。数据库中的所有行都有各自的音频文件链接。我想要的是

  1. 当我点击数据表的任何一行时,浏览器应该会自动重定向到各自音频文件的链接。
  2. 存储在数据库中的当前链接用于本地 IP。我想在用户被重定向之前更改到我的公共 IP 的链接,因为本地 IP 在远程服务器上不起作用。以下是我的代码:

数据表.php

 <?php
    /* Database connection start */
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "vici";

    $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());

    /* Database connection end */


    // storing  request (ie, get/post) global array to a variable  
    $requestData= $_REQUEST;


    $columns = array( 
    // datatable column index  => database column name
        0 =>'recording_id', 
        1 => 'call_date',
        2=> 'location',
        3=> 'Agent',
        4=> 'phone'
    );

    // getting total number records without any search
    $sql = "SELECT recording_id, call_date, location,agent,phone";
    $sql.=" FROM goautodial_recordings_view";
    $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
    $totalData = mysqli_num_rows($query);
    $totalFiltered = $totalData;  // when there is no search parameter then total number rows = total number filtered rows.


    $sql = "SELECT recording_id, call_date, location,agent,phone";
    $sql.=" FROM goautodial_recordings_view WHERE 1=1";
    if( !empty($requestData['search']['value']) ) {   // if there is a search parameter, $requestData['search']['value'] contains search parameter
        $sql.=" AND ( recording_id LIKE '".$requestData['search']['value']."%' ";    
        $sql.=" OR call_date LIKE '".$requestData['search']['value']."%' ";
        $sql.=" OR agent LIKE '".$requestData['search']['value']."%' )";
    }
    $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
    $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. 
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
    /* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc  */    
    $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");

    $data = array();
    while( $row=mysqli_fetch_array($query) ) {  // preparing an array
        $nestedData=array(); 

        $nestedData[] = $row["recording_id"];
        $nestedData[] = $row["call_date"];
        $nestedData[] = $row["location"];
        $nestedData[] = $row["agent"];
        $nestedData[] = $row["phone"];

        $data[] = $nestedData;
    }



    $json_data = array(
                "draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
                "recordsTotal"    => intval( $totalData ),  // total number of records
                "recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
                "data"            => $data   // total data array
                );

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

    ?>

index.php

<!DOCTYPE html>
<html>
    <title>GO VOIP</title>
    <head>
        <link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">
        <script type="text/javascript" language="javascript" src="js/jquery.js"></script>
        <script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
        <script type="text/javascript" language="javascript" >
            $(document).ready(function() {
                var dataTable = $('#employee-grid').DataTable( {
                    "processing": true,
                    "serverSide": true,
                    "ajax":{
                        url :"employee-grid-data.php", // json datasource
                        type: "post",  // method  , by default get
                        error: function(){  // error handling
                            $(".employee-grid-error").html("");
                            $("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
                            $("#employee-grid_processing").css("display","none");

                        }
                    }
                } );

            $('.dataTable').on('click', 'tbody td', function() {

  //get textContent of the TD
  alert('TD cell textContent : ', this.textContent)

  //get the value of the TD using the API 
  ('value by API : ', table.cell({ row: this.parentNode.rowIndex, column : this.cellIndex }).data());
})
            } );
        </script>
        <style>
            div.container {
                margin: 0 auto;
                max-width:760px;
            }
            div.header {
                margin: 100px auto;
                line-height:30px;
                max-width:760px;
            }
            body {
                background: #f7f7f7;
                color: #333;
                font: 90%/1.45em "Helvetica Neue",HelveticaNeue,Verdana,Arial,Helvetica,sans-serif;
            }
        </style>
    </head>
    <body>
        <div class="header"><h1>DataTable demo (Server side) in Php,Mysql and Ajax </h1></div>
        <div class="container">
            <table id="employee-grid"  cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
                    <thead>
                        <tr>
                            <th>Recording ID</th>
                            <th>Call date</th>
                            <th>Location</th>
                            <th>Agent</th>
                            <th>Phone</th>
                        </tr>
                    </thead>
            </table>
        </div>
    </body>
</html>

以下是截图:

【问题讨论】:

  • 为什么不直接使用ajax获取数据呢?然后手动添加到表中,最后初始化数据表?
  • 请解释如何做到这一点@Kishor
  • 我可以得到服务器的地址吗?这样我就可以发布一个 js fiddle。
  • @Amir 你第二个问题的答案UPDATE yourTable SET feild_of_ip = REPLACE (feild_of_ip, 'localip', 'remoteip') WHERE feild_of_ip LIKE '%localip%' ---- UPDATE goautodial_recordings_view SET location = REPLACE (location, 'http://192.168.0.164', 'http://233.465.23.34') WHERE location LIKE '%http://192.168.0.164%'

标签: javascript php mysql ajax datatable


【解决方案1】:

方法一:
SQL 查询中的更改(仅在您获得行数的地方)

$sql = "SELECT recording_id, call_date, CONCAT('<a href="',location,'">get song</a>'),agent,phone";

注意:如果你在 mysql 中有一些字段,比如 song_name,那么你会显示在锚标签中

$sql = "SELECT recording_id, call_date, CONCAT('<a href="',location,'">',song_name,'</a>'),agent,phone";

方法二:
PHP while 循环的变化
//替换为

$nestedData[] = $row["location"];

$nestedData[] = '<a href="'.$row["location"].'">get song</a>';

【讨论】:

    【解决方案2】:
    $(document).ready(function() {
          $.ajax({
            type: "POST",
            url: "employee-grid-data.php",
            success: function(data){
              data = JSON.parse(data);
              /*Here you will get the data
                Loop through the data and append to dataTable*/
              $('#employee-grid').DataTable();
            },
            error : function() { // error handling
                $(".employee-grid-error").html("");
                $("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
                $("#employee-grid_processing").css("display", "none");
              }
          });
    

    使用ajax从服务器获取JSON数据并手动添加到HTML表中,最后初始化datatable。

    【讨论】:

      【解决方案3】:

      你可以在简单的 php 中使用 eco 来做到这一点:

      echo '<a href="'.$stringwiththelink.'">Name of the song</a>';
      

      如果你点击它,它会将你重定向到文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 2012-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-04
        相关资源
        最近更新 更多