【发布时间】:2021-05-09 05:08:36
【问题描述】:
所以我正在制作一个简单的 Web 应用程序来测试 Ajax,由于某种原因,我收到 JSON.parse 错误,尽管我使用 json_encode($results) 将结果作为 JSON 返回。
该应用程序让我选择一个客户并提取该客户的订单
JS 文件:
function getOrders(clientId) {
$.ajax(
{
type: 'POST',
url: "AjaxRequests.php",
data : {
action: 'showOrders',
clientId: clientId
},
dataType : 'json',
success: function(results){
alert(results);
},
error: function(request, status, error){
console.log(clientId);
console.log(request.responseText);
console.log('error : ' + error);
console.log('status' + status);
},
}
)
};
AjaxRequests.php 文件
<?php
header('Content-Type: application/json; charset=UTF-8');
require_once './GestionClients.php';
if (isset($_POST['action'])) {
if ($_POST['action'] == 'showOrders') {
$clientId = $_POST['clientId'];
$gc = new GestionClients();
$results = $gc->getCmdsByClient($clientId);
echo json_encode($results);
}
}
?>
这是我从选择列表中选择一个客户端(本示例中的第一个客户端,在数据库中 ID = 1)后在控制台中得到的结果:
1 script.js:16:25
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}] script.js:17:25
error : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data script.js:18:25
statusparsererror
我尝试将 JSON 结果放在在线 JSON 解析器上,它看起来还不错。 感谢您的宝贵时间。
【问题讨论】:
-
“连接成功!”在哪里来自(哪里?那是在PHP的响应中吗?因为如果是这样,那是你的问题,因为它绝对不是有效的 JSON。
-
愚蠢的我,删除实际有效的,你能向我解释为什么它是相关的吗?应该离问题不远了吧?
-
Connection successfull![{"id":...不是有效的 JSON。这是 JavaScript 接收到的字符串。