I'm get and json array on ajax success.我只是在我的控制器类上对其进行编码,然后在成功时获取它。这是我的 json
var info = {
"full_name" : "Ray Villalobos",
"title" : "Staff Author",
"links" : [
{
"blog" : "http://example.com",
"facebook" : "http://facebook.com/example",
"youtube" : "http://www.youtube.com/example",
"podcast" : "http://feeds.feedburner.com/example",
"twitter" : "http://twitter.com/example"
},
{
"blog" : "http://example.com",
"facebook" : "http://facebook.com/example",
"youtube" : "http://www.youtube.com/example",
"podcast" : "http://feeds.feedburner.com/example",
"twitter" : "http://twitter.com/example"
},
{
"blog" : "http://example.com",
"facebook" : "http://facebook.com/example",
"youtube" : "http://www.youtube.com/example",
"podcast" : "http://feeds.feedburner.com/example",
"twitter" : "http://twitter.com/example"
}
]
};
现在,如果我的链接只有一个数据集而不是数组,我将像这样检索键和值:
for ( key in info.links ) {
if (info.links.hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' + info.links[key] + '">' + key + '</a>' + '</li>';
} //if the links has the key property
} // for...go through each link
如何在循环中检索数组键,值?
我不确定你在这里想做什么,但在"为了......在"循环中,这里的键是数组的索引。您可以使用以下代码获取链接:
var link = info.links[key];
然后检索相关属性,在您的情况下,属性可以是"link.blog"或"link.facebook"等。
for (infolink in info.links){
for ( key in infolink ) {
if (infolink.hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' + infolink[key] + '">' + key + '</a>' + '</li>';
} //if the links has the key property
} // for...go through each link
}
这里的数组 info.links 的元素不是数组。 info.links的值是对象,所以你不能像这样检索"blog/facebook/youtube"。 键的输出将为"0/1/2"
所以你可以试试这个
for(var key in info.links){
document.write('<li><a href="'+info.links[key].blog+'">Blog</a></li>');
document.write('<li><a href="'+info.links[key].facebook+'">Facebook</a></li>');
document.write('<li><a href="'+info.links[key].youtube+'">YouTube</a></li>');
document.write('<li><a href="'+info.links[key].podcast+'">Podcast</a></li>');
document.write('<li><a href="'+info.links[key].twitter+'">twitter</a></li>');
document.write('<hr/>');
}
终于得到了我所期望的。代码如下:
var output = "";
var linksCount = info.links;
for (var counter = 0; counter < linksCount.length; counter++) {
for ( key in infolink[counter]) {
if (infolink[counter].hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' + infolink[key][counter] + '">' + key[counter] + '</a>' + '</li>';
} //if the links has the key property
} // for...go through each link
}