我正在对端点进行REST调用,并且遇到了一个问题,即内部属性保留字符串而不转换为Javascript。
这就是我得到的:
"43750": {
"taskId": 43750,
"statusId": 1,
"set_at": "2019-03-27 16:20:51",
"userId": 2,
"value": "[{\"text\":\"Recreational Vehicle\"}]" <-- Problem
},
这是我应该得到的(旧的API响应):
"43750": {
"userId": "2",
"timestamp": "2019-03-27 16:20:51",
"value": [
{
"text": "Recreational Vehicle"
}
],
"statusId": "1"
},
这些是Chrome“ DevTools”网络部分的“响应”标签中的摘录。
由于某种原因,没有将对象数组解析为javascript,而是其余字符串。我已在PHP中将Content Type设置为json,并在请求中使用了json数据类型。我想念什么?
前端
$.ajax({
type: 'POST',
dataType: 'json',
url: API_URL,
data: {
action: 'getProject',
projectId: this.getActiveProjectId()
},
success: function (response) {
console.log('[AJAX RESPONSE] LOAD ACTIVE PROJECT', response);
debugger;
}
});
后端
<?php
$default_options = [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$pdo = new PDO(
sprintf(
"dblib:host=%s;dbname=%s",
$server,
$database
),
$user,
$pass,
$default_options
);
/* Determine action, handle request */
/* Do PDO Query */
$tasks = $statement->fetchAll();
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
echo json_encode($tasks, JSON_PRETTY_PRINT);
编辑:
有关旧API的详细信息:
前端是相同的。后端由MariaDB,PHP和mysqli_ *命令组成。我现在正在将其转换为使用SQL Server 2008和PDO。
最后一个API只是这样做了:
$SQL = 'SELECT * FROM Project WHERE projectId='.$projectId;
$project = mysqli_fetch_assoc(mysqli_query($db, $SQL));
while ($taskRow = mysqli_fetch_assoc($result)) {
$project['tasks'][$taskRow['taskId']] = [
'userId' => $taskRow['userId'],
'timestamp' => $taskRow['timestamp'],
'value' => json_decode($taskRow['dataValue']),
'statusId' => $taskRow['statusId']
];
}
$SQL = 'SELECT * FROM Task WHERE projectId='.$projectId.' ORDER BY timestamp ASC';
$result = mysqli_query($db, $SQL);
while ($commentRow = mysqli_fetch_assoc($result)) {
$project['tasks'][$commentRow['taskId']]['comments'][] = [
'text' => $commentRow['commentText'],
'timestamp' => $commentRow['timestamp'],
'userId' => $commentRow['userId']
];
}
header("Access-Control-Allow-Origin: *");
json_encode([
'success' => true,
'project' => $project
], JSON_PRETTY_PRINT);
答案 0 :(得分:2)
表中的value
列包含一个JSON
字符串。您要么需要先解码它,然后才能发送响应:
foreach ($tasks as &$task) {
$task['value'] = json_decode($task['value']);
}
或在JavaScript中完成
success: function(response) {
response.forEach(r => r.value = JSON.parse(r.value));
// rest of success function
}