为了账号安全,请及时绑定邮箱和手机立即绑定

无法使用 php 格式化来自 mysql 数据库的 DataTables 数据

无法使用 php 格式化来自 mysql 数据库的 DataTables 数据

PHP
宝慕林4294392 2023-07-01 16:40:05
我正在使用 dataTables 插件来处理一些数据。我使用的是 mysql 数据库和 php。我可以显示数据库中的数据,但无法对其进行格式化。我有一些字段是美元金额,我想添加美元符号和数千个逗号。谁能告诉我该怎么做吗?dataTables 中的列属性对我不起作用,因为列是在 php 文件中定义的。下面的代码有效,但我无法格式化我的货币列。HTML:<table id="example" class="display desktop" style="">        <thead>            <tr>                <th></th>                <th>Name</th>                <th>Title</th>                <th>Company</th>                <th>2019 Compensation</th>                <th>Median Employee Pay</th>                <th>Type of Position</th>                <th>Stock Price Change (2018-19)</th>                <th>2018 Compensation</th>                <th>Compensation Increase (2018-19)</th>            </tr>        </thead>        <tfoot>            <tr>               <th></th>                <th>Name</th>                <th>Title</th>                <th>Company</th>                <th>2019 Compensation</th>                <th>Median Employee Pay</th>                <th>Type of Position</th>                <th>Stock Price Change (2018-19)</th>                <th>2018 Compensation</th>                <th>Compensation Increase (2018-19)</th>            </tr>        </tfoot>    </table>jQuery:$('#example').DataTable( {    "processing": true,    "serverSide": true,    "ajax": "php/getTables.php"} );来自 getTables.php 文件的 PHP。这是从教程中复制的。我刚刚插入了我的数据库详细信息。
查看完整描述

1 回答

?
达令说

TA贡献1821条经验 获得超6个赞

您可以添加回调以在 php 或 javascript 中进行格式化。


后端解决方案:


$columns = array(

  array( 'db' => 'fortunateID',  'dt' => 0 ),

  array( 'db' => 'name',  'dt' => 1 ),

  array( 'db' => 'title',     'dt' => 2 ),

  array( 'db' => 'company',     'dt' => 3 ),

  array( 'db' => 'compensation2019',     'dt' => 4 ),

  array( 'db' => 'median-employee-pay',

         'dt' => 5,

         'formatter' => function( $d, $row ) {   

            return '$ '. number_format($number, 2);

        } ),

  array( 'db' => 'type-of-position',     'dt' => 6 ),

  array( 'db' => 'stock-price-change-2018-19',     'dt' => 7 ),

  array( 'db' => 'compensation2018',     'dt' => 8 ),

  array( 'db' => 'compensation-increase',     'dt' => 9 )   

);

或者您可以在前端进行格式化:


$('#example').DataTable( {

    "processing": true,

    "serverSide": true,

    "ajax": "php/getTables.php"

    "columnDefs" : [

      {

        "targets": [3,4,6,7,8] //currency columns (0 indexed)

        "render": function ( data, type, row, meta ) {

                     let num = parseInt(data); //cast to number

                     let formatted = Number(num.toFixed(1)).toLocaleString();

                     return '$ ' + formatted; 

                 }

      }

 ]

} );


查看完整回答
反对 回复 2023-07-01
  • 1 回答
  • 0 关注
  • 91 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信