Javascript 清除错误的JSON字符串
我尝试使用一个web服务,它返回JavaScript无法直接解析的JSON数据。我使用jqueryajax调用,在Chrome开发人员控制台中得到错误消息“uncaughtsyntaxerror:Unexpected token:”。我怎样才能解决这个问题?以下是我从服务中获得的示例:Javascript 清除错误的JSON字符串,javascript,jquery,json,Javascript,Jquery,Json,我尝试使用一个web服务,它返回JavaScript无法直接解析的JSON数据。我使用jqueryajax调用,在Chrome开发人员控制台中得到错误消息“uncaughtsyntaxerror:Unexpected token:”。我怎样才能解决这个问题?以下是我从服务中获得的示例: { "DepartureBoard":{ "noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestDepartureBoard.
{
"DepartureBoard":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestDepartureBoard.xsd",
"error":"No journeys found",
"errorText":"There was no journey found for the requested board or time.",
"$":""
}
}
这是我的密码。执行下面的错误函数
$.ajax({
crossDomain: true,
type: 'GET',
contentType: "application/json; charset=utf-8",
url: myurl,
dataType: 'jsonp',
jsonpCallback: 'onSuccess',
cache: false,
success: function (data) {
this.onSuccess( data );
},
error: function (data) {
// prints debug messages now
}
});
更新:我正在请求远程资源。这似乎使事情复杂化了
更新2:也许我走错了方向。我认为解析JSON数据很简单,但正如一些人指出的那样,它的格式似乎是错误的
更新3:我找到了一个解决方法。通过使用函数调用
file\u get\u contents($url)
创建一个最小的PHP文件,我可以对自己的服务器进行AJAX调用。有了JSONP和一些受下面答案启发的修改,我让它工作起来了。(不经意间,用minimal.php文件而不是.html文件包装所有内容实际上解决了另一个问题;我的JavaScript文件正在被缓存。)您不需要解析它。它已经是一个对象了。如何在服务器端输出json?尝试此客户端:
$(document).ready(function() {
$.getJSON(myurl + '?callback=?', 'param=value', function(result) {
console.log(result.DepartureBoard.errorText);
});
});
应调出:“未找到请求的板或时间的行程。”
另外,如果后端是PHP,那么您应该:
$error = array(
"DepartureBoard" => array(
"noNamespaceSchemaLocation" => "http://yoururl.xsd",
"error" => "No journeys found",
"errorText" => "There was no journey found...",
"$" => ""
)
);
header('Content-Type: text/javascript; charset=utf8');
echo $_GET['callback'] . '(' . json_encode($error) . ')';
您正在请求JSONP,但返回的不是JSONP。JSONP不是JSON。JSONP实际上只是一个JavaScript文件。您希望响应为:
onSuccess({
"DepartureBoard":{
"noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestDepartureBoard.xsd",
"error":"No journeys found",
"errorText":"There was no journey found for the requested board or time.",
"$":""
}
});
注意对象是如何包装在函数调用中的
另外,$.ajax
调用中的某些参数不正确
contentType
设置请求的Content type
头,它是请求主体的内容类型。这与反应无关。摆脱它
只有当服务器不接受回调
参数作为GET参数时,才需要jsonpCallback
。这仅适用于服务器使用硬编码字符串作为回调名称的情况
如果没有它,jQuery将向URL追加callback=someFunctionName
,并期望JSONP响应将其用作回调名称
例如,JSONP响应应该是(这里以PHP为例):
最后,
this.onSuccess(数据)代码>在你的成功中
可能不会做你认为它会做的事情。我建议去掉那条线。在您的success
函数中,数据将是调用返回的对象。我实际使用的是相同的服务,这就是
var tripQuestion = "https://api.vasttrafik.se/bin/rest.exe/v1/trip?authKey=" + authKey + "&format=json&jsonpCallback=searchForTripJSON" + "&numTrips=6";
if (time && date) tripQuestion = tripQuestion + "&date=" + date + "&time=" + time;
if (departure.id) tripQuestion = tripQuestion + "&originId=" + departure.id
if (destination.id) tripQuestion = tripQuestion + "&destId=" + destination.id
else tripQuestion = tripQuestion + "&destCoordLat=" + destination.lat+ "&destCoordLong=" + destination.lon+ "&destCoordName=" + destination.name
$.ajax({
crossDomain: true,
type: 'GET',
async: true,
contentType: "application/json; charset=utf-8",
url: tripQuestion,
dataType: 'jsonp',
jsonpCallback: 'searchForTripJSON',
jsonp: false,
cache: false,
success: function (data) {
//put success code here
},
error: function (data) {
//put error code here
},
complete: function (data) {
//put complete code here
}
希望这有帮助您确定是json问题吗?根据,这是有效的json…这是有效的json,您是如何解析它的?您列出的响应似乎缺少“填充”的。JSON字符串应该包装在函数调用中,这样响应就可以被解析为JavaScript。这个错误是因为JavaScript将前导的{
表示一个而不是对象
.Odd。jQuery API说,永远不应该为jsonp调用错误处理程序:“注意:跨域脚本和跨域jsonp请求不调用此处理程序。”对于对远程资源的JSONP请求,您正在使用的以下参数将被忽略:crossDomain,contentType
。此外,对于JSONP和脚本请求,缓存默认为false,因此也不需要。您的请求失败,因为服务不支持JSONP,或者您使用的服务不正确y、 请参阅所述服务的文档。我在控制台中遇到此错误:XMLHttpRequest无法加载***************&format=json&id=1&direction=2?callback=onSuccess。请求的资源上不存在“访问控制允许源代码”头。因此,不允许访问源代码“”。我删除了authKey)这是因为这个答案中的代码调用的是json请求,而不是jsonp请求。onSuccess
应该替换为?
,然后jquery将用自己的回调函数名填充它。这当然会让你回到原点,因为服务没有正确使用回调参数。在我的answe中r我修改了代码以正确发送getJSON中的参数。@AlexShilman我更新了问题:我正在请求一个远程资源。这之前不清楚。这会改变什么吗?我刚才尝试时遇到了相同的错误:XMLHttpRequest无法加载…@David,jsonp仅用于从远程源获取数据。我已经更新了我的answer、 这样试试。你也可以发布服务器端代码。输出的代码。很遗憾,我无法控制远程资源返回的内容。@David:JSONP需要在远程服务器上启用。响应的形式必须是:onSuccess({})
。如果它没有包装在函数调用中,它将无法工作。如果远程服务器没有返回JSONP响应,那么您需要找到另一个解决方案。一个解决方案是使用您的服务器作为远程服务器的代理。谢谢,但我通过包装PHP代码找到了另一个解决方案。我想您只需先将其下载到服务器。Di你试过我的解决方案吗?我刚才试过。它成功了,但我需要结束AJAX函数调用(代码>)编码>并注释掉变量。
var tripQuestion = "https://api.vasttrafik.se/bin/rest.exe/v1/trip?authKey=" + authKey + "&format=json&jsonpCallback=searchForTripJSON" + "&numTrips=6";
if (time && date) tripQuestion = tripQuestion + "&date=" + date + "&time=" + time;
if (departure.id) tripQuestion = tripQuestion + "&originId=" + departure.id
if (destination.id) tripQuestion = tripQuestion + "&destId=" + destination.id
else tripQuestion = tripQuestion + "&destCoordLat=" + destination.lat+ "&destCoordLong=" + destination.lon+ "&destCoordName=" + destination.name
$.ajax({
crossDomain: true,
type: 'GET',
async: true,
contentType: "application/json; charset=utf-8",
url: tripQuestion,
dataType: 'jsonp',
jsonpCallback: 'searchForTripJSON',
jsonp: false,
cache: false,
success: function (data) {
//put success code here
},
error: function (data) {
//put error code here
},
complete: function (data) {
//put complete code here
}