问题
I can't for the life of me figure out how to access the values inside this object. Any help would be much apreciated
End goal, once I can access the link, i'll iterate each and append and img tag to the dom after the images-header element.
JS to consume json
$("#stack_name").focusout(function() {
var name = $(this).val();
// alert(name);
$.getJSON('/images.json?name='+ name, function(data) {
console.log("DATA: ", data);
// $('<p>Test</p>').appendTo('.images-header');
});
});
Console Log outputs:
DATA:
Object {data: Object}
data: Object
images: Array[4]
0: "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Connecticut_in_United_States.svg/270px-Connecticut_in_United_States.svg.png"
1: "http://www.enchantedlearning.com/usa/states/connecticut/map.GIF"
2: "https://familysearch.org/learn/wiki/en/images/0/01/Connecticut-county-map.gif"
3: "http://www.ct.gov/ecd/lib/ecd/20/14/state%2520of%2520connecticut%2520county%2520outline.jpg"
length: 4
__proto__: Array[0]
__proto__: Object
__proto__: Object
app-init.js?body=1:15
/images.json?name=connecticut
{
"data": {
"images": [
"http://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Connecticut_in_United_States.svg/270px-Connecticut_in_United_States.svg.png",
"http://www.enchantedlearning.com/usa/states/connecticut/map.GIF",
"https://familysearch.org/learn/wiki/en/images/0/01/Connecticut-county-map.gif",
"http://www.ct.gov/ecd/lib/ecd/20/14/state%2520of%2520connecticut%2520county%2520outline.jpg"
]
}
}
回答1:
You can access images array like this, you have have to parse json string using $.parseJSON
img1 = jsonObj.data.Images[0];
Live Demo
You can iterate through array using for loop
for(i=0; i < jsonObj.data.images.length; i++)
{
alert(jsonObj.data.images[i]);
}
回答2:
Try
Fiddle Demo
$("#stack_name").focusout(function()
{
var name = $(this).val();
$.getJSON('/images.json?name='+ name, function(data)
{
var images = data.data.images;
var $header = $('.images-header');
for(var index in images )
{
var $image = $('<img><img/>');
var link = images[index];
$image.attr("src", link);
$header.append($image);
}
});
});
来源:https://stackoverflow.com/questions/17775144/jquery-get-link-values-from-data-object