I have a little app that pulls data from several API's. In all of my cases so far I get JSON back for a single response, but for this one I get an array of hits. How do I access the data in the array?? Here's the basic structure of my javascript grabbing data from the returned JSON:
// pull article from JSON
function getArticle(article) {
document.getElementById('articletitle').innerHTML = (article.title);
...
};
So that works great for a single response, it grabs the article title and throws it in a div. But what if开发者_高级运维 I get back an array of articles like this
JSON:
getArticle({"Title":"title","Rights":"Copyright (C)",...[{"ResultId":1,"DocType":"ar","DocTitle":"some title",...
My main question is just how to grab say the DocTitle
here of a given article? simply grabbing .DocTitle
doesn't seem to get through. BONUS POINTS for modifying the javascript to iterate through the array of articles returned too.
Thanks a million.
In your question this:
getArticle({"Title":"title","Rights":"Copyright (C)",...
[{"ResultId":1,"DocType":"ar","DocTitle":"some title",...
Has been over-abbreviated to the point that we have to guess what you meant. You can't have an array sitting in the middle of an object unless it is associated with a key. You need something like this:
getArticle({"Title":"title","Rights":"Copyright (C)",...
"articles" : [{"ResultId":1,"DocType":"ar","DocTitle":"some title",...]
});
function getArticle(article) {
alert(article.articles[0].DocTitle); // first item in array: "some title"
for (var i = 0; i < article.articles.length; i++) {
var currentArticle = article.articles[i];
alert(currentArticle.ResultId + ": " + currentArticle.DocTitle);
}
}
Note I've added the key "articles" within your object.
Or you can return an array on its own instead of as part of another object:
getArticle([{"ResultId":1,"DocType":"ar","DocTitle":"some title",...},{"ResultId":2,...},...]);
function getArticle(articles) {
for (var i = 0; i < articles.length; i++)
alert(articles[i].DocTitle);
}
[{"ResultId":1,"DocType":"ar","DocTitle":"some title"},{"ResultId":2,"DocType":"ar","DocTitle":"some title"}] This array should have an index too.
var test={"Title":"title",content:[{"ResultId":1,"DocType":"ar","DocTitle":"some title"},{"ResultId":2,"DocType":"ar","DocTitle":"some title"}]};
alert(test.content[0].DocTitle);
精彩评论