我想获取一个json,只在div中显示syn。
就像: -
$.getJSON('http://words.bighugelabs.com/api/2/eba286cdc7f3619674544d80ce94cb1b/stack/json', function(data) {
//parse the response to display in a div
});
来自链接的JSON标记:
{
"noun": {
"syn": [
"batch",
"deal",
"flock",
"good deal",
"great deal",
"hatful",
"heap",
"lot",
"mass",
"mess",
"mickle",
"mint",
"muckle",
"peck",
"pile",
"plenty",
"pot",
"quite a little",
"raft",
"sight",
"slew",
"spate",
"tidy sum",
"wad",
"push-down list",
"push-down stack",
"smokestack",
"push-down storage",
"push-down store",
"agglomerate",
"chimney",
"cumulation",
"cumulus",
"large indefinite amount",
"large indefinite quantity",
"list",
"listing",
"memory device",
"mound",
"storage device",
"whole lot",
"whole slew"
]
},
"verb": {
"syn": [
"pile",
"heap",
"arrange",
"lade",
"laden",
"load",
"load up",
"set up"
],
"rel": [
"heap up",
"pile up",
"stack away",
"stack up"
]
}
}
答案 0 :(得分:1)
您还没有提到您正在运行的问题。如果你在域名上运行已发布的代码'words.bighugelabs.com',那么你可以在你的回调函数中访问:
data.verb.syn
或任何其他属性。如果您不在该域上,那么您可能会遇到与跨域脚本限制相关的问题。如果是这种情况,您将需要查看JSONP(如果远程服务器支持它)或代理方法。
答案 1 :(得分:1)
好的,我从您提供的网址中看到了JSON响应。你可以做这样的事情(你可以通过使用StringBuilder
来提高效率):
var list;
var syn = data.noun.syn;
for(var i = 0; i < syn.length; i++)
{
list += syn[i];
}
syn = data.verb.syn;
for(var i = 0; i < syn.length; i++)
{
list += syn[i];
}
$('#mydiv').append(list);
将来,请更具体地说明您面临的问题 -
答案 2 :(得分:1)
由于同源策略,JSON无法加载,只需将?callback=?
附加到您的世界并且它可以正常工作。更新的代码,
$.getJSON('http://words.bighugelabs.com/api/2/eba286cdc7f3619674544d80ce94cb1b/stack/json?callback=?', function(data) {
//parse the response to display in a div
//you can access the JSON object from the data object.
});
更新
当您将?callback=?
附加到$.getJSON
中使用的URL时,jQuery会理解它是JSONP请求而不是XMLHttpRequest来获取JSON。实际上回调参数可以是任何东西,但值必须是?
才能触发JSONP请求。
在发出请求时,jQuery会将参数替换为?callback=jQuery15107307685413397849_1299439987443
,每次发出请求时,该值都是唯一的。