【发布时间】:2016-07-27 15:58:26
【问题描述】:
我正在尝试从 PHP 脚本返回 JSON 以填充 DataTable。
这是名为 '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 文件的更下方,我格式化了 Datatable(现在我想了想,我不确定我是否需要这个):
<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
我以前也有过这种情况,但一直无法从中恢复。
【问题讨论】:
-
data: data,在您的 jQuery 代码中...也许您想在通过 ajax 发送数据变量之前对其进行初始化,或者如果不需要则根本不包含它
标签: javascript php jquery json datatables