我在我的一个HTML文件中使用以下代码
var queryURL = encodeURI(yahooUrl + loc + appId);
alert(queryURL);
$.getJSON(queryURL, function(data){
alert('inside getJSON')
alert(data);
var items = [];
$.each(data, function(key, value){
items.push('<li id="' + key + '">' + value + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});`
其中queryURL
是一个大查询,如果我从浏览器的地址栏加载,我会得到一个包含JSON对象的文件。但是下面的代码不起作用,整个JSON对象显示在Firefox的错误控制台上,错误“无效标签”。我在查询字符串的末尾添加了&callback=?
,如SO中的一些答案所述。
任何人都可以建议我做错了吗?
修改:for
queryURL =“http://where.yahooapis.com/geocode?location=107,South%20Market,San%20Jose,San%20Fransico,Leusina,USA,&flags=J&appid=dj0yJmk9SUk0NkdORm9qM2FyJmQ9WVdrOU1tVnFUVzlVTm5NbWNHbzlORFl4TnpZME5UWXkmcz1jb25zdW1lcnNlY3JldCZ4PWE1&callback= ?“
我收到以下错误:
Error: invalid label
Source File: http://where.yahooapis.com/geocode?location=107,South%20Market,San%20Jose,San%20Fransico,Leusina,USA,&flags=J&appid=dj0yJmk9SUk0NkdORm9qM2FyJmQ9WVdrOU1tVnFUVzlVTm5NbWNHbzlORFl4TnpZME5UWXkmcz1jb25zdW1lcnNlY3JldCZ4PWE1&callback=jQuery16404719878257064011_1316606312366&_=1316608283354
Line: 1, Column: 1
源代码:
{"ResultSet":{"version":"1.0","Error":0,"ErrorMessage":"No error","Locale":"us_US","Quality":87,"Found":1,"Results":[{"quality":39,"latitude":"37.336849","longitude":"-121.847710","offsetlat":"37.338470","offsetlon":"-121.885788","radius":34800,"name":"","line1":"","line2":"San Jose, CA","line3":"","line4":"United States","house":"","street":"","xstreet":"","unittype":"","unit":"","postal":"","neighborhood":"","city":"San Jose","county":"Santa Clara County","state":"California","country":"United States","countrycode":"US","statecode":"CA","countycode":"","uzip":"","hash":"","woeid":2488042,"woetype":7}]}}
答案 0 :(得分:5)
这可能是因为jQuery自动切换到使用JSONP(因为它是跨域请求)和Yahoo apparently doesn't use JSONP but regular JSON。您是否尝试过使用$.ajax()
的好dataType:"JSON"
?
使用$ .ajax :
$.ajax({
url: queryURL,
dataType: "JSON",
success: function(data){
alert('inside getJSON')
alert(data);
var items = [];
$.each(data, function(key, value){
items.push('<li id="' + key + '">' + value + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
}
});
让我在这里非常好,因为我有一个可怕的日子:Working example