如何使用服务器端处理(PHP)填充jquery datatable? [英] How to populate a jquery datatable using server side processing (PHP)?

查看:584
本文介绍了如何使用服务器端处理(PHP)填充jquery datatable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用服务器端PHP脚本填充数据表,该脚本与Postgres表(〜75K行)的数据相呼应。我按照 datatable页面中提供的步骤执行,但表格不显示任何数据。这是我这么久以来:



jsp文件中的表定义:

 < table id =myTableclass =table table-stripedwidth =100%> 
< thead>
< tr>
< th> idpersona< / th>
< th< thipapellido< / th>
< primernombre< / th>
< th> numeroidentificacion< / th>
< f> fechanacimiento< / th>
< / tr>
< / thead>
< tfoot>
< tr>
< th> idpersona< / th>
< th< thipapellido< / th>
< primernombre< / th>
< th> numeroidentificacion< / th>
< f> fechanacimiento< / th>
< / tr>
< / tfoot>
< / table>

这是我的初始化表的功能。我尝试了几个小时(我是一个新手的程序员)找到正确的文件夹,我必须放置PHP文件。现在它在我的apache服务器的htdocs文件夹中(所以我可以从/localhost/tablabd.php访问它)。这是正确的方法吗?

 < script type =text / javascriptlanguage =javascriptclass = init> 
$(document).ready(function(){
$('#myTable')。dataTable({
Processing:true,
ServerSide
sAjaxSource:http://localhost/tablabd.php
});
});
< / script>

最后是PHP脚本。当我在浏览器中输入localhost / tablabd.php时,所有的数据都被正确读取。但是当我执行我的Java项目时,它不会在表'myTable'中显示任何东西。

 <?php 
/ *
*脚本:DataTable PHP和PostgreSQL的服务器端脚本
*版权所有:2010 - Allan Jardine
*许可证:GPL v2或BSD(3点)
* /

/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*容易设置的变量
* /

/ *应读取并发送回DataTable的数据库列数组。使用一个空格,其中
*要插入非数据库字段(例如计数器或静态图像)
* /
$ aColumns = array(idpersona,primerapellido primernombre,numeroidentification,fechanacimiento);

/ *索引列(用于快速准确的表基数)* /
$ sIndexColumn ='idpersona';

/ *要使用的数据库表* /
$ sTable ='tpersonas';

/ *数据库连接信息* /
$ gaSql ['user'] =postgres;
$ gaSql ['password'] =******;
$ gaSql ['db'] =sisben;
$ gaSql ['server'] =localhost;



/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*如果您只想使用PHP服务器端的DataTables基本配置,则
*不需要在此行下方进行编辑
* /

/ *
* DB连接
* /
$ gaSql ['link'] = pg_connect(
host = $ gaSql ['server']。
dbname =。$ gaSql ['db']。
user =。$ gaSql ['user']。
=。$ gaSql ['password']
)或死('无法连接:'pg_last_error());


/ *
*分页
* /
$ sLimit =;
if(isset($ _GET ['iDisplayStart'])&& $ _GET ['iDisplayLength']!='-1')
{
$ sLimit =LIMIT。 intval($ _GET ['iDisplayStart'])。OFFSET。
intval($ _GET ['iDisplayLength']);



/ *
*订购
* /
if(isset($ _GET ['iSortCol_0']))
{
$ sOrder =ORDER BY; ($ i = 0; $ i< intval($ _GET ['iSortingCols']); $ i ++)
{
if($ _GET ['bSortable _'。 ['iSortCol _'。$ i])] ==true)
{
$ sOrder。= $ aColumns [intval($ _GET ['iSortCol _'。$ i])]
($ _ GET ['sSortDir _'。$ i] ==='asc'?'asc':'desc')。,;
}
}

$ sOrder = substr_replace($ sOrder,,-2);
if($ sOrder ==ORDER BY)
{
$ sOrder =;
}
}


/ *
*过滤
*注意这是假设正在搜索的字段是一个字符串类型字段(即可以使用ILIKE的一个
*)。布尔字段等将需要修改。
* /
$ sWhere =;
if($ _GET ['sSearch']!=)
{
$ sWhere =WHERE(;
for($ i = 0; $ i& ($ aColumns); $ i ++)
{
if($ _GET ['bSearchable _'。$ i] ==true)
{
$ sWhere。= $ aColumns [$ i]。ILIKE'%。pg_escape_string($ _GET ['sSearch'])。%'OR;
}
}
$ sWhere = substr_replace($ sWhere, ,-3);
$ sWhere。=);
}

/ *个人列过滤* /
($ i = 0; $ i< count($ aColumns); $ i ++)
{
如果($ _GET ['bSearchable _'。$ i] ==true&&$ _GET ['sSearch _'。$ i]!='')
{
if sWhere ==)
{
$ sWhere =WHERE;
}
else
{
$ sWhere。=AND;
}
$ sWhere。= $ aColumns [$ i]。ILIKE'%pg_escape_string($ _ GET ['sSearch _'。$ i])。%'
}
}


$ sQuery =
SELECT.str_replace(,,,implode(,,$ aColumns )
FROM $ sTable
$ sWhere
$ sOrder
$ sLimit
;
$ rResult = pg_query($ gaSql ['link'],$ sQuery)或死(pg_last_error());

$ sQuery =
SELECT $ sIndexColumn
FROM $ sTable
;
$ rResultTotal = pg_query($ gaSql ['link'],$ sQuery)或者死(pg_last_error());
$ iTotal = pg_num_rows($ rResultTotal);
pg_free_result($ rResultTotal);

if($ sWhere!=)
{
$ sQuery =
SELECT $ sIndexColumn
FROM $ sTable
$ sWhere
;
$ rResultFilterTotal = pg_query($ gaSql ['link'],$ sQuery)或者死(pg_last_error());
$ iFilteredTotal = pg_num_rows($ rResultFilterTotal);
pg_free_result($ rResultFilterTotal);
}
else
{
$ iFilteredTotal = $ iTotal;
}



/ *
*输出
* /
$ output = array(
sEcho => intval($ _ GET ['sEcho']),
iTotalRecords=> $ iTotal,
iTotalDisplayRecords=> $ iFilteredTotal,
aaData=> ; array()
);

while($ aRow = pg_fetch_array($ rResult,null,PGSQL_ASSOC))
{
$ row = array();

($ i = 0; $ i< count($ aColumns); $ i ++)
{
if($ aColumns [$ i] =='idpersona'
{
/ *'ID'列的特殊输出格式* /
$ row [] =($ aRow [$ aColumns [$ i]] ==0)? ' - ':$ aRow [$ aColumns [$ i]];
}
else if($ aColumns [$ i]!='')
{
/ *一般输出* /
$ row [] = $ aRow [ $ aColumns [$ i]];

}
}
$ output ['aaData'] [] = $ row;
}

echo json_encode($ output);

//免费结果集
pg_free_result($ rResult);

//关闭连接
pg_close($ gaSql ['link']);
?>

和在broswer中脚本输出的示例:也许我没有列映射某个地方?

  {sEcho:0,iTotalRecords:74047,iTotalDisplayRecords:74047,aaData [e71657b3-a7f5-4a10-bc43-d0edbeb5cdab,PEREZ,ABDON,4299249,1947-07-10 00:00:00],[796db2d4-fee3-4cca-ae06-429a2ea6c5af ,TORREZ,MARIA,24240762,1951-09-17 00:00:00]]} 

这是在我访问包含表的应用程序页面时,Firebug显示的信息:

  _ 1440905636814 
列[0] [数据] 0
列[0] [名称]
列[0] [可订购] true
列[0] [搜索] regex] false
列[0] [search] [value]
列[0] [可搜索] true
列[1] [数据] 1
列[1] [名称]
列[1] [可订购] true
列[1] [搜索] [regex]假
列[1] [搜索] [价值]
列[1 ] [searchable] true
columns [2] [数据] 2
列[2] [名称]
列[2] [可订购] true
列[2] [搜索] [regex] false
列[2] [search] [value]
列[2] [可搜索] true
列[3] [数据] 3
列[3] [名称]
列[3] [
列[3] [search] [regex] false
列[3] [search] [value]
列[3] [可搜索] true
columns [ 4] [data] 4
列[4] [名称]
列[4] [可订购] true
列[4] [搜索] [regex] false
列[ 4] [search] [value]
列[4] [可搜索] true
draw 1
length 20
order [0] [column] 0
order [ 0] [dir] asc
search [regex] false
search [value]
开始0

提前感谢

解决方案


解决方案


正确的选项名称为 bProcessing bServerSide 。您的DataTable初始化代码应该是:

  $('#myTable')。dataTable({
bProcessing true,
bServerSide:true,
sAjaxSource:/tablabd.php
});




注意


我已将URL更改为 /tablabd.php ,因为如果您的HTML和PHP位于不同的域,除非您允许跨域请求,否则Ajax调用可能会失败。确保您的HTML和PHP位于同一个域。


I'm trying to populate a datatable with a server side PHP script which echoes the data from a postgres table (~75K rows). I followed the steps given in the datatable page and implemented it, but the table doesn't show any data. This is what I have so long:

table definition in a jsp file:

<table id="myTable" class="table table-striped" width="100%">
                            <thead>
                                <tr>
                                    <th>idpersona</th>
                                    <th>primerapellido</th>
                                    <th>primernombre</th>
                                    <th>numeroidentificacion</th>
                                    <th>fechanacimiento</th>
                                </tr>
                            </thead>
                            <tfoot>
                                <tr>
                                    <th>idpersona</th>
                                    <th>primerapellido</th>
                                    <th>primernombre</th>
                                    <th>numeroidentificacion</th>
                                    <th>fechanacimiento</th>
                                </tr>
                            </tfoot>
                        </table>

Here is my function to initialise the table. I tried for hours (I'm a newbie programmer) to find the right folder where I must place the PHP file. Right now it is in the htdocs folder of my apache server (so I can access it from /localhost/tablabd.php). Is this the right way to do it?

<script type="text/javascript" language="javascript" class="init">
    $(document).ready(function() {
        $('#myTable').dataTable( {
            "Processing": true,
            "ServerSide": true,
            "sAjaxSource": "http://localhost/tablabd.php"
        } );
    } );
    </script>

And finally the PHP script. When I type localhost/tablabd.php in my browser, all the data is fetched correctly. But when I execute my Java project, it doesn't show anything in the table 'myTable'.

<?php
    /*
     * Script:    DataTables server-side script for PHP and PostgreSQL
     * Copyright: 2010 - Allan Jardine
     * License:   GPL v2 or BSD (3-point)
     */

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Easy set variables
     */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array("idpersona", "primerapellido","primernombre", "numeroidentificacion", "fechanacimiento");

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = '"idpersona"';

    /* DB table to use */
    $sTable = '"tpersonas"';

    /* Database connection information */
    $gaSql['user']       = "postgres";
    $gaSql['password']   = "******";
    $gaSql['db']         = "sisben";
    $gaSql['server']     = "localhost";



    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP server-side, there is
     * no need to edit below this line
     */

    /*
     * DB connection
     */
    $gaSql['link'] = pg_connect(
        " host=".$gaSql['server'].
        " dbname=".$gaSql['db'].
        " user=".$gaSql['user'].
        " password=".$gaSql['password']
    ) or die('Could not connect: ' . pg_last_error());


    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
        $sLimit = "LIMIT ".intval( $_GET['iDisplayStart'] )." OFFSET ".
            intval( $_GET['iDisplayLength'] );
    }


    /*
     * Ordering
     */
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc').", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }


    /*
     * Filtering
     * NOTE This assumes that the field that is being searched on is a string typed field (ie. one
     * on which ILIKE can be used). Boolean fields etc will need a modification here.
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $_GET['bSearchable_'.$i] == "true" )
            {
                $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string( $_GET['sSearch'] )."%' OR ";
            }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ")";
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string($_GET['sSearch_'.$i])."%' ";
        }
    }


    $sQuery = "
        SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";
    $rResult = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());

    $sQuery = "
        SELECT $sIndexColumn
        FROM   $sTable
    ";
    $rResultTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
    $iTotal = pg_num_rows($rResultTotal);
    pg_free_result( $rResultTotal );

    if ( $sWhere != "" )
    {
        $sQuery = "
            SELECT $sIndexColumn
            FROM   $sTable
            $sWhere
        ";
        $rResultFilterTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
        $iFilteredTotal = pg_num_rows($rResultFilterTotal);
        pg_free_result( $rResultFilterTotal );
    }
    else
    {
        $iFilteredTotal = $iTotal;
    }



    /*
     * Output
     */
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = pg_fetch_array($rResult, null, PGSQL_ASSOC) )
    {
        $row = array();

        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $aColumns[$i] == 'idpersona' )
            {
                /* Special output formatting for 'ID' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            }
            else if ( $aColumns[$i] != ' ' )
            {
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];

            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );

    // Free resultset
    pg_free_result( $rResult );

    // Closing connection
    pg_close( $gaSql['link'] );
?>

and a sample of the output of the script in the broswer: maybe I'm missing a column mapping somewhere?

{"sEcho":0,"iTotalRecords":74047,"iTotalDisplayRecords":74047,"aaData":[["e71657b3-a7f5-4a10-bc43-d0edbeb5cdab","PEREZ","ABDON","4299249","1947-07-10 00:00:00"],["796db2d4-fee3-4cca-ae06-429a2ea6c5af","TORREZ","MARIA","24240762","1951-09-17 00:00:00"]]}

Here is the info Firebug shows when I access the page on my application which contains the table:

_   1440905636814
columns[0][data]    0
columns[0][name]    
columns[0][orderable]   true
columns[0][search][regex]   false
columns[0][search][value]   
columns[0][searchable]  true
columns[1][data]    1
columns[1][name]    
columns[1][orderable]   true
columns[1][search][regex]   false
columns[1][search][value]   
columns[1][searchable]  true
columns[2][data]    2
columns[2][name]    
columns[2][orderable]   true
columns[2][search][regex]   false
columns[2][search][value]   
columns[2][searchable]  true
columns[3][data]    3
columns[3][name]    
columns[3][orderable]   true
columns[3][search][regex]   false
columns[3][search][value]   
columns[3][searchable]  true
columns[4][data]    4
columns[4][name]    
columns[4][orderable]   true
columns[4][search][regex]   false
columns[4][search][value]   
columns[4][searchable]  true
draw    1
length  20
order[0][column]    0
order[0][dir]   asc
search[regex]   false
search[value]   
start   0

Thanks in advance.

解决方案

SOLUTION

Correct option names are bProcessing and bServerSide. Your DataTables initialization code should be:

$('#myTable').dataTable({
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "/tablabd.php"
});

NOTES

I have changed URL to /tablabd.php because if your HTML and PHP are on different domain, Ajax calls may fail unless you allow cross-domain requests. Make sure you have HTML and PHP on the same domain.

这篇关于如何使用服务器端处理(PHP)填充jquery datatable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆