Reputation: 7794
I have an ashx page that returns the following JSON data that I would like to be able to loop through and add to values to a bunch of li's in a ul.
My question is how do I loop through to retrieve the values.
The data that is returned from the ashx look slike this
{"ImageCollection":
{
"Images":
[
{
"ImageID":"62",
"CatID":"1",
"Location":"/Images/62.gif",
"FullHeight":"466","FullWidth":"606"
},
{
"ImageID":"63",
"CatID":"1",
"Location":"/Images/63.gif",
"FullHeight":"205",
"FullWidth":"751"
}
]
}
}
and if I try this
<script type="text/javascript">
$.getJSON("/Service/GetJson.ashx?data=images", function(data) {
var jsObjectData = eval(data);
$.each(data, function(i, item) {
alert(data[i].ImageID);
});
});
</script>
I get a single alert that says undefined. What am I doing wrong?
Upvotes: 2
Views: 1132
Reputation: 630419
There's no need to eval in this case, you can just do this:
$.getJSON("/Service/GetJson.ashx?data=images", function(data) {
var jsObjectData = data.ImageCollection.Images;
$.each(jsObjectData, function(i, item) {
alert(item.ImageID);
});
});
$.getJSON()
already converts it to an object, so just treat it like that, data
is the overall object, and inside you want to loop though the ImageCollection.Images
, so pass that to your $.each()
call.
Upvotes: 7