我正在尝试从 PHP 脚本返回 JSON 以填充数据表。
这是名为“api/exceptions_all.php”的 PHP 脚本:
<?php
$select = "SELECT '', [FOR_PARTNER], [FOR_NAME] FROM [brokerage].[dbo].[for_exceptions]";
$query = sqlsrv_query($dbc, $select);
$out = array();
while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) )
{
$out[] = $row;
}
echo json_encode($out);
?>
当我在浏览器中提取文件时,我可以看到 JSON,并且它的格式正确:
[{"":"","FOR_PARTNER":"0000111222","FOR_NAME":"CUSTOMER1 "},{"":"","FOR_PARTNER":"0000333111","FOR_NAME":"CUSTOMER2"}]
这是我尝试用来检索 JSON 的 jQuery:
$(document).ready(function()
{
$.ajax({
type: 'GET', // not sure if I should use POST or GET
url: 'api/exceptions_all.php',
dataType: 'json',
async: false,
data: data,
success: function(data)
{
console.log(data); // I'm guessing the success is where I should populate the table rows
},
fail: function()
{
console.log('fail');
}
});
});
这是我最初设置表格的 HTML:
<table class='table table-bordered display nowrap' id='example1' cellspacing='0' width='100%'>
<thead>
<tr>
<th><!--column used for editing--></th>
<th>Partner Code</th>
<th>Partner Name</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- this is where the datatable rows should be displayed -->
</tbody>
</table>
在同一个 HTML 文件中,我格式化了数据表(现在我考虑一下,我不确定是否需要这个):
<script type="text/javascript">
table = $('#example1').DataTable({
"iDisplayLength": 25,
"autoWidth": true,
"scrollX": true,
"scrollY": 550,
"stateSave": true,
"dataType": "json"
});
</script>
完成所有这些后,我收到一个控制台错误,内容如下:
Uncaught ReferenceError: data is not defined
我以前也遇到过这种情况,但一直无法恢复。
最佳答案
您似乎没有通过 AJAX 将数据传递到 PHP 脚本“api/exceptions_all.php”。
所以你的 jQuery 代码中不需要这一行
数据:数据
删除它,您收到的错误就会消失
关于javascript - jQuery DataTable 在文档就绪时返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617959/