我正在使用 PHP 脚本创建 JSON 数据。它看起来像这样:
{"Id":0}
现在,如果我将它放入一个文件中,然后使用 ajax 加载它就没问题了。但是如果我从 PHP 脚本中请求它,我会得到 p>
parsererror | SyntaxError: Unexpected token ILLEGAL
这是我用来从 PHP 加载 JSON 的代码:
$.ajax({
url: 'check.php',
data: {
username: 'LOL',
password: '1234'
},
dataType: 'json',
type: 'POST',
success: function(data) {
$('#result').html('#Id=' + data.Id);
},
error: function(jqXHR, textStatus, errorThrown) {
$('#result').html(textStatus + ' | ' + errorThrown);
}
});
这是 PHP 代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
echo '{"Id":0}';
?>
有什么想法吗?
最佳答案
文档类型属于 HTML 文档,而不是 JSON。
在你的 PHP 文件中尝试这样的东西(而且只有这个)
<?php
header('Content-Type: application/json');
?>
{"Id":0}
鉴于您发布的内容,我什至看不出有任何理由涉及 PHP。我猜你只发布了一个非常简单的例子。如果它变得更复杂,涉及服务器端处理、数据检索等,例如使用 PHP 的 json_encode()
<?php
header('Content-Type: application/json');
$data = array(
'Id' => 0,
'foo' => $someOtherComplexVariable
);
echo json_encode($data);
exit;
关于php - 使用 PHP 创建 JSON 数据并使用 jQuery 解析它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6325695/