这是我从数据表子行获得的代码
$(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']]
} );
首先,您需要更改此行:
"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
),
本质上有一个行数组。
根据达伦的回答,我是这样解决的:
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);
表.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']]
} );