我从 PHP 文件中获取 JavaScript 中的一些 JSON 数据。
为了使用数据,我使用 JSON.parse(json_response)
,除非我在 PHP 中使用 JSON header ,否则它可以正常工作:
header('Content-Type: application/json');
使用时,我在控制台中收到以下消息:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
目前我只是选择使用 PHP header()
或 JS JSON.parse()
并发现 this useful question .
看起来就像为我的 JS 脚本设置一个 JSON header “自动解析”JSON。
- 这是正常行为吗?可能是什么原因导致的?
- 我该怎么办?在
header()
和JSON.parse()
之间随机选择可能不是一个好主意。
实际代码:
index.chart.php:
<?php
header('Content-Type: application/json');
// [...] <- config lines, no output
// Dummy data for Chart.js
$data = [
'labels' => ['test', 'a', 'z', 'e', 'r', 't'],
'datasets' => [
[
'label' => 'First',
'backgroundColor' => 'rgb(63, 123, 249)',
'borderColor' => 'rgb(31, 117, 219)',
'data' => [
20, 10, 30, 45, 51.2, 5
],
'fill' => false
]
]
];
echo json_encode($data);
?>
index.chart.js:
window.addEventListener('DOMContentLoaded', function () {
// jQuery Ajax
$.get('assets/inc/index.chart.php').done(function (json) {
var response = JSON.parse(json);
console.log(response);
}).fail(function (error) {
window.console.log(error);
});
});
最佳答案
如果您没有指定dataType
,那么 jQuery 将使用 Content-Type
header 确定从 URL 接收的数据类型,并通过适当的方法运行它。解析器。
json
不是一个 JSON 字符串,它是解析 JSON 得到的 JavaScript 对象。
JSON.parse
的输入需要是 JSON 字符串。
更改:
function (json) { var response = JSON.parse(json);
致:
function (response) {
关于javascript - PHP JSON header 导致 JSON.parse 出错(使用 jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51969156/