简体   繁体   English

如何遍历JSON数据?

[英]How to loop through JSON Data?

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. 我有一个ashx页面,该页面返回以下JSON数据,这些数据我希望能够遍历并添加到ul中一堆li的值中。

My question is how do I loop through to retrieve the values. 我的问题是如何循环检索值。

The data that is returned from the ashx look slike this 从ashx返回的数据看起来像这样

{"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? 我究竟做错了什么?

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. $.getJSON()已经将其转换为对象,所以就这样对待, data是整体对象,并且在内部要遍历ImageCollection.Images ,因此将其传递给您的$.each()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM