我正在尝试使用返回JavaScript无法直接解析的JSON数据的Web服务。我使用jQuery AJAX调用并在Chrome开发人员控制台中收到错误消息“Uncaught SyntaxError:Unexpected token:”。我怎样才能解决这个问题?以下是我从服务中获得的一个示例:
{
"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 :我找到了解决方法。通过使用函数call file_get_contents($url)
创建一个最小的PHP文件,我可以对我自己的服务器进行AJAX调用。通过JSONP以及受以下答案启发的一些修改,我得到了它的工作。 (不小心,将所有内容包装在最小的.php文件中而不是.html实际上解决了另一个问题;我的JavaScript文件正在被缓存。)
答案 0 :(得分:2)
您正在请求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
标题,它是 请求正文<的内容类型/ EM> 即可。它与响应无关。摆脱它。
仅当服务器不接受jsonpCallback
参数作为GET参数时,才需要callback
。它仅适用于服务器使用硬编码字符串作为回调名称的情况。
没有它,jQuery会将callback=someFunctionName
附加到您的URL,并期望JSONP响应将其用作回调名称。
例如,JSONP响应应该是(在这里使用PHP作为示例):
echo $_GET['callback'].'('.json_encode($data).');';
最后,this.onSuccess( data );
内的success
可能不会按照您的想法执行。我建议删除该行。在success
函数data
内部将是通话中返回的对象。
答案 1 :(得分:1)
我实际上是在使用相同的服务,这就是
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
}
希望这会有所帮助
答案 2 :(得分:0)
你不应该解析它。它已经是一个对象了。你是如何在服务器端输出json的?试试这个客户端:
$(document).ready(function() {
$.getJSON(myurl + '?callback=?', 'param=value', function(result) {
console.log(result.DepartureBoard.errorText);
});
});
应安排出来:&#34;找不到所要求的董事会或时间的旅程。&#34; 附:如果它是后端的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) . ')';