$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt", //here
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
}, //and here to fetch the data below
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
我想通过使用ajax从SQL查询中获取数据。这是我的SQL查询:
$tsql =
"SELECT *
FROM [dbo].[ITEM_MASTER] A
INNER JOIN
[dbo].[STOCK] B
ON
B.ItemId = A.ItemId
";
$result = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if (!$result) {
die("Query to show fields from table failed");
}
while($row=sqlsrv_fetch_array($result))
{
$ItmId = $row['ItemId'];
$ItmName = $row['ItemName'];
$ItmType = $row['ItemType'];
$ItmGroup = $row['ItemGroup'];
$ItmClass = $row['ItemClass'];
$ItmSerialNum = $row['ItemSerialNum'];
$ItmUOM = $row['ItemUOM'];
$StkQty = $row['StockQuantity'];
$StkId = $row['StockId'];
}
在ajax部分,我只是调用变量的名称,如$ItmId
,或者像我在while循环中所说的那样。
可能吗?如果是这样,怎么样?因为我对AJAX没有任何了解
更新
数据被推送到第二个参数而没有显示ItmId
?无论我是否更改$data : ItmName
,它只是根据数组显示并显示其他内容?
$(document).ready(function() {
var table = $('#table').DataTable( {
"ajax": {
"url": "table_data.php",
"type": "POST"
},
"columns": [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "$data": "ItmId" },
{ "$data": "ItmName" },
{ "$data": "ItmGroup"},
{ "$data": "ItmClass"}
],
"order": [[1, 'asc']]
} );
答案 0 :(得分:4)
首先,您需要更改此行:
"ajax": "../ajax/data/objects.txt", //here
指向将运行sql查询以获取数据的实际文件:例如:
"ajax": {"url": "path/to/phpfile.php", "type": "POST"}
你需要像这样进行while
循环:
$data = array();
while($row=sqlsrv_fetch_array($result))
{
$ItmId = $row['ItemId'];
$ItmName = $row['ItemName'];
$ItmType = $row['ItemType'];
$ItmGroup = $row['ItemGroup'];
$ItmClass = $row['ItemClass'];
$ItmSerialNum = $row['ItemSerialNum'];
$ItmUOM = $row['ItemUOM'];
$StkQty = $row['StockQuantity'];
$StkId = $row['StockId'];
$data['data'][] = array($ItmId, $ItmName, $ItmType,....etc);
}
echo json_encode($data);
您应该注意,您需要实际表格中的确切数量的列(html)。 另外,你的json应该是这样的:
data:
array(
ItmId,
ItmName,
..etc
),
array(
ItmId,
ItmName,
..etc
),
基本上有一个行数组。
答案 1 :(得分:1)
根据Darren的回答,我解决了这个问题:
<强> table_data.php 强>
$data = array();
while($row=sqlsrv_fetch_array($result))
{
$data['data'][] = array(
'ItmId' => $row['ItemId'],
'ItmName' => $row['ItemName'],
'ItmType' => $row['ItemType'],
'ItmGroup' => $row['ItemGroup'],
'ItmClass' => $row['ItemClass'],
'ItmSerialNum' => $row['ItemSerialNum'],
'ItmUOM' => $row['ItemUOM'],
'StkQty' => $row['StockQuantity'],
'StkId' => $row['StockId']
);
}
echo json_encode($data);
table.php (我在哪里显示我的HTML)
$(document).ready(function() {
var table = $('#table').DataTable( {
"ajax": {
"url": "table_data.php",
"type": "POST"
},
"columns": [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "ItmId"},
{ "data": "ItmName"},
{ "data": "ItmClass"},
{ "data": "ItmUOM"}
],
"order": [[1, 'asc']]
} );