我收到以下错误。我不确定我在JSON中获得'
符号的位置。我已经仔细检查过并确保PHP的json_encode
函数没有在第一个位置添加'符号。
我在StackOverflow中看到过其他问题和解决方案,但在Google中找不到任何其他解决方案。
SyntaxError: Unexpected token ' in JSON at position 0
at parse (<anonymous>)
at e.parseJSON (jquery-migrate.min.js:2)
at fn (jquery.min.js:6)
at k (jquery.min.js:6)
at XMLHttpRequest.<anonymous> (jquery.min.js:6)
下面是生成JSON字符串的PHP代码。
$info = Embed\Embed::create($videoUrl);
$result = array();
$result['title'] = $info->title;
$result['desciption'] = $info->description;
$result['type'] = $info->type;
$result['tags'] = $info->tags;
$result['provider'] = $info->providerName;
echo json_encode($result,true);
以下是用于执行后期操作的jQuery。
$(document).ready(function () {
$("#videoUrl").blur(function (event) {
if ($(this).val() != '') {
$.ajax({
type: 'POST',
url: '/url-here',
dataType: 'json',
data: {
"value": $(this).val()
},
success: function (msg) {
alert("Data Saved: " + msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown.message);
}
})
}
});
});
Chrome控制台中提供的示例响应仅供参考。
'{"title":"Inside of big gold mine in Africa. How it works. Documentary.","desciption":"Deepest mine in Africa.","type":"video","tags":["Megastructures","mine","gold","deepest mine","documentary","Deepest","how it works"],"provider":"YouTube"}
修改
根据要求,我正在分享整个PHP代码。
public function getVideoDetails() {
OW::getResponse()->clearHeaders();
OW::getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8');
$videoUrl = $_POST['value'];
$info = Embed\Embed::create($videoUrl);
$result = array();
$result['title'] = $info->title;
$result['description'] = $info->description;
$result['type'] = $info->type;
$result['tags'] = $info->tags;
//$result['image'] = $info->image;
$result['provider'] = $info->providerName;
echo json_encode($result, true);
OW::getResponse() - > sendHeaders();
exit;
}
答案 0 :(得分:2)
A common reason for unexpected leading characters in the response of PHP is that there is a character before the <?php
in any of the included/involved php scripts.