【发布时间】:2016-10-06 11:55:29
【问题描述】:
我有一个函数可以在文档准备好时填充 DataTable。
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php',
"dataType": "json",
"bDestroy": true,
"stateSave": true
});
// this portion reloads the datatable without refreshing the page
setInterval(function() {
$dataTable.ajax.reload();
}, 60000);
}
所以现在我想添加一个搜索功能。它基本上会使用从服务器返回的搜索数据重新填充 DataTable。
正下方是检索用户输入参数的jQuery:
$('#searchSubmit').on('click', function()
{
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
$.ajax({
url:'api/qnams_all.php',
type:"POST",
data:{searchbooking: searchbooking, searchquote: searchquote},
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
dataType:"json"
}).done(function(response){
console.log(response.data)
}).fail(function(){
alert('error');
}).always(function(){
alert('done');
});
});
这是在 api/qnams_all.php 中找到的 PHP 进程:
<?php
include("../include/database.php");
include("../include/sessions.php");
$_SESSION['where'] = "";
$searchbooking = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchbooking']))));
$searchquote = strip_tags(mysqli_real_escape_string($dbc, trim(strtoupper($_POST['searchquote']))));
// build the WHERE clause
if($searchbooking != ""){
$_SESSION['where'] = "booking = '".$searchbooking."'";
}
if($searchquote != ""){
if( $_SESSION['where'] != "" )
$_SESSION['where'] .= " AND ";$_SESSION['where'] .= "quote = '".$searchquote."'";
}
// check if WHERE is blank
if($_SESSION['where'] == ""){$where = "where TLI_COMPLETE = 'N'";}
else{$where = $_SESSION['where'];}
// run the query
$select = "SELECT
CONCAT('\"',COALESCE(booking,''),'\"')
,CONCAT('\"',COALESCE(quote,''),'\"')
FROM
searchTable " . $where . "";
$query = mysqli_query($dbc, $select) or die(mysqli_error());
$resnum = mysqli_num_rows($query);
echo "{\"data\":[";
$i = 1;
while($row = $query->fetch_assoc())
{
echo "[";
echo implode(', ', $row);
echo "]";
if($i < $resnum){
echo ",";
}
$i++;
}
}
echo "]}";
mysqli_free_result($query);
?>
上面的 PHP 进程与 $(document).ready() 函数完美配合。
我的问题是:如何操作我的代码,以便搜索功能与 ready() 功能一起使用?
现在,搜索功能位于ready() 功能之外。我可以在ready() 函数中应用搜索功能吗?如果是这样,AJAX 调用会是什么样子?
目前,它读取:
"ajax": 'api/qnams_all.php'
如果我能够将搜索添加到 ready() 函数,这个 AJAX 调用会改变吗?
就一个问题而言,如何将搜索功能添加到ready() 函数中,以便我可以在最初显示数据,然后在用户决定搜索记录时重新填充数据?
【问题讨论】:
-
我建议您查看 columns(x).search() 函数,您可以对初始数据中的列执行实时搜索,而无需调用 api
标签: javascript php jquery datatables