- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我设置了我的 DataTable,从我的数据库正确返回数据并且过滤确实有效,但我遇到的问题是每列的选择框只显示第一页数据之外的值。
我想我必须在我的 PHP 中执行某种类型的 DISTINCT
查询,但我不知道如何将其导入 JavaScript 以及如何使用 DataTables。
这是我目前所拥有的:
HTML/JS:
<table id="mainTable" class="table table-hover table-bordered table-striped table-condensed" >
<thead>
<tr>
<th>ID</th>
<th>UserID</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>UserID</th>
</tr>
</tfoot>
</table>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#mainTable').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "<?php echo url(); ?>/new/datatables.php?sSearch=1&bSearchable_0=1&bSearchable_1=1&sEcho=1&sOrder=1",
initComplete: function () {
var api = this.api();
api.columns().indexes().flatten().each( function ( i ) {
var column = api.column( i );
var select = $('<select><option value="">All</option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? ''+val+'' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'" style="min-width:95px;">'+d+'</option>' )
} );
} );
},
"aLengthMenu": [20, 10, 20, 25, 50],
"oLanguage": {
"sLoadingRecords": "<h4 style='float:left;'>Loading...</h4> <img src='<?php echo url(); ?>/img/common/loading3.gif' style='float:right;'>"
},
"pagingType": "full_numbers",
"sDom": "<'container-fluid'<'span6'<'pull-left'T>><'span6'<'pull-right'f>>r>t<'clear'>rt<'container-fluid'<'span6'<'pull-left'i>><'span6'<'pull-right'p>>>",
"oTableTools": {
"sSwfPath": "<?php echo url(); ?>/new/app/DataTables/extensions/TableTools/swf/copy_csv_xls_pdf.swf",
"aButtons": [
{
"sExtends": "csv",
"sFileName": "Pick Lines - *.csv",
"sButtonText": "Export to CSV",
},
{
"sExtends": "xls",
"sFileName": "Pick Lines - *.xls",
"sButtonText": "Export to EXCEL (xls)",
},
"copy", "print"
]
}
} );
} );
</script>
PHP:
<?php
$serverName = ""; //serverName\instanceName
$connectionInfo = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
/*
* Script: DataTables server-side script for PHP and MySQL
* 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( 'ID', 'UserID');
/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "ID";
/* DB table to use */
$sTable = "ActivityLog";
/*
* Paging
*/
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "OFFSET ".$_GET['iDisplayStart']." ROWS
FETCH NEXT ".$_GET['iDisplayLength']." ROWS ONLY ";
}
/*
* Ordering
*/
$sOrder = "";
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] ) ]."
".addslashes( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$_GET['bSearchable_'.$i] = "true";
if ( isset($_GET['sSearch_'.$i]) && !empty($_GET['sSearch_'.$i]))
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".addslashes($_GET['sSearch_'.$i])."%' ";
}
else {
$sWhere .= "";
}
}
/*
* SQL queries
* Get data to display
*/
$sQuery = "
SELECT ID, UserID
FROM
$sTable
$sWhere
$sOrder
$sLimit
";
$rResult = sqlsrv_query($conn, $sQuery ) or die(print_r(sqlsrv_errors()));
/* Data set length after filtering */
$sQueryRow = "
SELECT ID, UserID FROM $sTable
$sWhere
";
//echo $sQueryRow;
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sQueryRow , $params, $options );
$iFilteredTotal = sqlsrv_num_rows( $stmt );
/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM $sTable
";
$rResultTotal = sqlsrv_query($conn, $sQuery ) or die(print_r(sqlsrv_errors()));
$aResultTotal = sqlsrv_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
/*
* Output
*/
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = sqlsrv_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' 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 );
?>
我遇到的问题是它显示了 39 行,这是应该的,但是下拉列表只显示每个过滤器第一页上的前 20 行,就像在这个图像示例中,39 行但只有 1-20 到在下拉框上过滤。
当我进入下一页时,它仍然只显示前 20 个。
最佳答案
我对此进行了一些研究,但找不到任何示例代码,因此我提出了一个运行良好的解决方案。为了解释它的工作原理,我创建了一个函数,该函数在选择下拉的重点关注时会进行AJAX调用。我还向 datatables php 添加了一个 where 子句来处理过滤后的 json 数据的显示。
需要注意的一件重要事情是,我必须建立流量控制,因为如果使用其他 tabletools 元素,则在通过列进行过滤时会发生一些奇怪的行为。我的解决方案是清除使用表格工具时选择的过滤,以便监听大量事件。
HTML
<script type="text/javascript" language="javascript" src="./jquery-1.11.1.min.js"></script>
<script type="text/javascript" language="javascript" src="./jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="./dataTables.tableTools.min.js"></script>
<script type="text/javascript" language="javascript" class="init">
var where;
var selInitd = new Array();
var selectedData;
$(document).ready(function() {
function getSelectedList(str){
var response = new Array();
var returnArray = new Array();
$.ajax({
url: "./filter.php",
data: "selected="+str,
async: false,
success: function(msg){
response = msg.split(',');
//alert(response);
for(m = 0; m < response.length; m++){
response[m] = response[m].replace('[','');
response[m] = response[m].replace(']','');
response[m] = response[m].replace(/\"/g,'');
var val = response[m];
returnArray.push(val);
}
}
})
return returnArray;
}
var columnNumber = $('#example thead th').length;
//this can probably be handled in PHP
function colSelected(column){
switch(column){
case 0:
return "columnA";
break;
case 1:
return "columnB";
break;
case 2:
return "columnC";
break;
case 3:
return "columnD";
break;
case 4:
return "columnE";
break;
case 5:
return "columnF";
break;
case 6:
return "columnG";
break;
case 7:
return "columnH";
break;
case 8:
return "columnI";
break;
case 9:
return "columnJ";
break;
default:
return "columnA";
}
}
var table = $('#example')
.DataTable( {
scrollX: true,
dom: '<"top"fl>rt<"bottom"ipT><"clear">',
serverSide: true,
processing: true,
ordering: true,
order: [[ 9, "columnJ" ]],
ajax: {
url: "../dt.php",
data: function ( json ){
json.where = where;
},
},
tableTools: {
sRowSelect: "os",
sSwfPath: "./copy_csv_xls_pdf.swf",
aButtons: [
{
sExtends: "collection",
sButtonText: "Save",
sButtonClass: "save-collection",
aButtons: [ 'copy', 'csv', 'xls', 'pdf' ]
},
'print'
]
},
initComplete: function (settings, json) {
var api = this.api();
//alert(Object.keys(settings.oPreviousSearch));
var col;
api.columns().indexes().flatten().each( function ( i ) {
selInitd[i] = false;
var column = api.column( i );
//made the column number the id for getElementById
var select = $('<select id=' + i + '><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
for (k = 0; k < columnNumber; k++){
//inefficient but gets every column selected every time any column is selected
var value = document.getElementById(k).value;
if (value != "" ){
//exposes the column names, you probably want to do this differently
col = colSelected(k);
//build where to send to php, you probably want to do this differently
if (where == null){
where = col + " = '" + value + "'";
}else{
where = where + " AND " + col + " = '" + value + "'";
}
}
}
api.ajax.reload( null, true );
where = null;
} )
.on( 'focus', function () {
if(!selInitd[i]){
var selectedL = getSelectedList(colSelected(i)).slice();
for(d = 0; d < selectedL.length; d++) {
select.append( '<option value="' + selectedL[d] + '">' + selectedL[d] + '</option>' )
}
selInitd[i] = true;
}
} );
} );
}
} );
//reset filter selections when text is entered in the search box
$(".dataTables_filter input")
.on("input.dt", function(e) {
//reset select inputs
for(h = 0; h < columnNumber; h++){
var value = document.getElementById(h);
value.selectedIndex = 0;
}
return;
});
//reset filter selections when sorting by column
$(".dataTables_scrollHeadInner th.sorting")
.on("click.dt", function(e) {
//reset select inputs
for(h = 0; h < columnNumber; h++){
var value = document.getElementById(h);
value.selectedIndex = 0;
}
return;
});
//reset filter selections page length widget is changed
$(".dataTables_length select")
.on("click.dt", function(e) {
//reset select inputs
for(h = 0; h < columnNumber; h++){
var value = document.getElementById(h);
value.selectedIndex = 0;
}
return;
});
//reset filter selections page number is changed
table.on("page.dt", function(e) {
//reset select inputs
for(h = 0; h < columnNumber; h++){
var value = document.getElementById(h);
value.selectedIndex = 0;
}
return;
});
} );
</script>
</head>
</body>
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>columnA</th>
<th>columnB</th>
<th>columnC</th>
<th>columnD</th>
<th>columnE</th>
<th>columnF</th>
<th>columnG</th>
<th>columnH</th>
<th>columnI</th>
<th>columnJ</th>
</tr>
</thead>
<tfoot>
<tr>
<th>columnA</th>
<th>columnB</th>
<th>columnC</th>
<th>columnD</th>
<th>columnE</th>
<th>columnF</th>
<th>columnG</th>
<th>columnH</th>
<th>columnI</th>
<th>columnJ</th>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
过滤 PHP
<?php
$column = $_GET['selected'];
//conection:
$link = mysqli_connect("ip.address","user","password","DB") or die("Error " . mysqli_error($link));
//consultation:
$query = "SELECT DISTINCT ".$column." FROM table ORDER BY ".$column." ASC" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
//display information:
$rows = array();
$rIdx = 0;
while($row = mysqli_fetch_array($result)) {
$rows[$rIdx] = $row[$column];
$rIdx++;
}
if($rows){
echo json_encode($rows);
}
DTPHP
<?php
/*
* DataTables example server-side processing script.
*
* Please note that this script is intentionally extremely simply to show how
* server-side processing can be implemented, and probably shouldn't be used as
* the basis for a large complex system. It is suitable for simple use cases as
* for learning.
*
* See http://datatables.net/usage/server-side for full details on the server-
* side processing requirements of DataTables.
*
* @license MIT - http://datatables.net/license_mit
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/
// DB table to use
$table = 'table';
// Table's primary key
$primaryKey = 'columnA';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array( 'db' => 'columnA', 'dt' => 0 ),
array( 'db' => 'columnB', 'dt' => 1 ),
array( 'db' => 'columnC', 'dt' => 2 ),
array( 'db' => 'columnD', 'dt' => 3 ),
array( 'db' => 'columnE', 'dt' => 4 ),
array( 'db' => 'columnF', 'dt' => 5 ),
array( 'db' => 'columnG', 'dt' => 6 ),
array( 'db' => 'columnH', 'dt' => 7 ),
array( 'db' => 'columnI', 'dt' => 8 ),
array( 'db' => 'columnJ', 'dt' => 9 )
);
// SQL server connection information
$sql_details = array(
'user' => 'user',
'pass' => 'password',
'db' => 'DB',
'host' => 'ip.address'
);
$whereAllClause = '';
if ($_GET['where'] != ''){
$whereAllClause = $_GET['where'];
$whereAllClause = str_replace('+', ' ', $whereAllClause);
$whereAllClause = str_replace('%3D', '=', $whereAllClause);
$whereAllClause = str_replace('%27', '\'', $whereAllClause);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP
* server-side, there is no need to edit below this line.
*/
require( './ssp.class.php' );
echo json_encode(
SSP::complex( $_GET, $sql_details, $table, $primaryKey, $columns, null, $whereAllClause )
);
关于javascript - PHP - DataTables 服务器端单独的列过滤仅提供第一页选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27299259/
场景 网站页面有一个带有分页、过滤、排序功能的表格 View 。 表中的数据是从REST API服务器获取的,数据包含数百万条记录。 数据库 REST API 服务器 Web 服务器 浏览器 问
我有一个表student,其中的列dte_date(日期)具有值(2019-01-01、2019-02-01、2019-03-01)。 .等) 条件: dte_date 列中没有重复值。 但 dte_
我有一些逻辑可以根据不活动的用户创建通知。我正在获取具有以下属性的用户列表。我想做的只是在部门有非 Activity 用户时触发我的创建通知方法。因此,给出下面的列表,基本上会创建 1 个通知,表示部
使用 GPS 开发跟踪应用程序。一切都很好,但有时由于封闭区域或恶劣天气,我得到的分数不准确。当您绘制它们时,它看起来不对,有很多跃点/跳跃。 我应该运行什么算法来过滤掉不良信号对我来说,这看起来像是
我正在尝试按变量类型过滤对象数组。节点是一个具有位置的对象,但以不同的方式定义——作为点、矢量或附件。这是一个代码: class Joint { var position:Position
我想做的是在向量上创建一个过滤器,以便它删除未通过谓词测试的元素;但不太确定我该怎么做。 我根据谓词评估输入向量中的每个元素,例如在我的代码中,is_even 仿函数在 device_vector 向
我是 Gremlin 的新手,我正在使用 Gremlin 3.0.2 和 Stardog 5.0。我编写此查询是为了找出 schema.org 本体中两个实体之间的路径。以下是输出 - gremlin
考虑以下示例数据表, dt 30 的那一行需要去 - 或者如果其中两行 > 30相隔几秒钟,删除所有 3 个。然而 ,当我们有 4 行或更多行时,我们需要删除时间差 > 30 没有另一对 < 30
我正在考虑使用 ZeroMQ,并尝试了一些示例。但是,我无法验证 ZeroMQ 是否支持一些重要的要求。我希望你能帮助我。 我将使用这个简单的场景来问我的问题: 出版商(例如交易所)提供(大量)股票的
我需要从我的查询中过滤掉大量的对象。目前,它正在抓取类中的所有对象,我想将其过滤为查询字符串中的相关对象。我怎样才能做到这一点?当我尝试时,我收到一个属性错误说明 ''QuerySet' object
如何在 Prometheus 查询中添加标签过滤器? kube_pod_info kube_pod_info{created_by_kind="ReplicaSet",created_by_name=
我有包含字符串的列的数据框,并希望过滤掉包含某些字符串以外的任何内容的所有行。考虑下面的简化示例: string % dplyr::filter(stringr::str_detect(string,
我有以下数据框,其中包含多行的角度变化值: 'data.frame': 712801 obs. of 4 variables: $ time_passed: int 1 2 3 4 5 6
我有一个 BehaviorSubject我希望能够filter ,但要保持新订阅者在订阅时始终获得一个值的行为主题式质量,即使最后发出的值被过滤掉。有没有一种简洁的方法可以使用 rxjs 的内置函数来
我有一个 RSS 提要,每天输出大约 100 篇文章。我希望过滤它以仅包含更受欢迎的链接,也许将其过滤到 50 个或更少。回到当天,我相信您可以使用“postrank”来做到这一点,但在谷歌收购后现已
我有这样一个重复的xml树- this is a sample xml file yellowred blue greyredblue 如您所见,每个项目可以具有不同数量的颜色标签
我以为我在 Haskell 学习中一帆风顺,直到... 我有一个 [[Int]] tiles = [[1,0,0] ,[0,1,0] ,[0,1,0]
我在使用 Knockout.js 过滤可观察数组时遇到问题 我的js: 包含数据的数组 var docListData = [ { name: "Article Name 1", info:
我在 mongoDB 中有这个架构: var CostSchema = new Schema({ item: String, value: Number }); var Attachm
给定一个数据框“foo”,我如何才能只选择“foo”中的那些行,例如foo$location =“那里”? foo = data.frame(location = c("here", "there",
我是一名优秀的程序员,十分优秀!