【发布时间】:2020-04-09 11:51:24
【问题描述】:
我正在尝试构建一个数据表来显示 ajax 数据库调用的结果。返回的 JSON 对象是正确的,如下所示:
[{"prof_id":"1","0":"1","prof_name":"Cole Test1","1":"Cole Test1","prof_SQL":"JUST SQL JAJA","2":"JUST SQL JAJA","date":null,"3":null},{"prof_id":"2","0":"2","prof_name":"Doobie Doobie","1":"Doobie Doobie","prof_SQL":"my SQL statement to be executed","2":"my SQL statement to be executed","date":null,"3":null},{"prof_id":"3","0":"3","prof_name":"Cole Test 2","1":"Cole Test 2","prof_SQL":"my SQL statement to be executed that is better than the last","2":"my SQL statement to be executed that is better than the last","date":null,"3":null}]
但是由于类型错误,数据表不会显示任何内容:
d 未定义
控制台中的错误消息。行号是 jquery.dataTables.min.js:62:257 但我不知道如何读取该文件,也无法确切弄清楚这意味着什么或问题出在哪里。
这是 index.php 页面上的表格:
<div>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>
prof_id
</th>
<th>
prof_name
</th>
</tr>
</thead>
</table>
</div>
<script src="includes/Scripts.js"></script>
这是包含 ajax 调用的 Scripts.js 文件:
function fetchQueries(){
$.ajax({
type: "GET",
url: "API.php",
datatype: "json"
}).done(function(returnresult) {
console.log(returnresult);
$(".query-div").text(returnresult);
$('#example').DataTable( {
"ajax": "API.php",
"columns": [
{ "data": "prof_id" },
{ "data": "prof_name" }
]
} );
})
}
fetchQueries()
最后是 API.php 文件,其中包含实际的数据库查询:
$object = new Dbh; //Create insteance of Dbh
$object->connect(); //Call the connect function to connect to db
$pdo = $object->getPdo(); //Call getPdo from Dbh to get an instance of the pdo
$prof_Query = $pdo->query('SELECT * FROM oogns_quries'); //Creating the db query
$prof_Query->execute();
echo '{"data"' . json_encode($prof_Query->fetchAll()) . '}';
编辑::
我发现问题在于服务器响应 ajax 调用的数据不是正确的 json 对象。所以我将它响应的内容输入到 JSONLint 中,发现:
{
"data" [{
"prof_id": "1",
"0": "1",
"prof_name": "Cole Test1",
"1": "Cole Test1",
"prof_SQL": "JUST SQL JAJA",
"2": "JUST SQL JAJA",
"date": null,
"3": null
}, {
"prof_id": "2",
"0": "2",
"prof_name": "Doobie Doobie",
"1": "Doobie Doobie",
"prof_SQL": "my SQL statement to be executed",
"2": "my SQL statement to be executed",
"date": null,
"3": null
}, {
"prof_id": "3",
"0": "3",
"prof_name": "Cole Test 2",
"1": "Cole Test 2",
"prof_SQL": "my SQL statement to be executed that is better than the last",
"2": "my SQL statement to be executed that is better than the last",
"date": null,
"3": null
}]
}
带有错误信息:
Error: Parse error on line 2:
{ "data" [{ "prof_id": "1",
---------^
Expecting 'EOF', '}', ':', ',', ']', got '['
但我不确定如何解决这个问题。任何建议都会很棒。
【问题讨论】:
-
您在哪里看到此错误消息?在浏览器控制台中?有行号之类的吗?
-
谢谢你的回复,很抱歉我看到这个我不得不离开我的房子。错误消息在控制台中,这是行号 jquery.dataTables.min.js:62:257 但其结果是我认为的某种 jquery 或 json 文件,因为我无法真正理解它。如果您需要,我可以以某种方式与您分享。
-
是的,这是来自 DataTables 内部某个地方的 JavaScript 错误。在这种情况下,很难知道哪里出了问题。但是,几乎可以肯定,问题出在您的初始化代码或 ajax 语句中。以下问题与您的问题非常相似:stackoverflow.com/questions/29893207/…
-
@ColePerry 我相信你需要这样做jsfiddle
-
@stanchacon 谢谢你们的帮助。今晚下班后我会努力解决这个问题,我会告诉大家的。
标签: php json sql-server ajax datatables