使用jQuery从JSON字符串获取值

时间:2013-10-04 06:13:23

标签: javascript jquery arrays json

我正在尝试使用少量数组和一些键:值对来解析JSON字符串。我现在能够从一个数组中获取值,但我也希望从另一个数组中获取值。数组具有相同的键,但我无法找到如何从第二个数组中获取数据。

我的jQuery脚本看起来像这样

$("a").click(function () {
    var page = $(this).text();
    console.log(page);
    $.post("/services/gallery/getimage", {"path[]":[<%=path %>], "page": page}, function(data){
        var length = data.previews.length;
        console.log(length);
        var html = "";
        for(var i = 0; i < length; i++){
            $.each(data.previews[i], function (index, value) {
                html+= "<a href=\""+value+"\"><img src=\""+value+"\" alt=\""+index+"\" /></a>";
                console.log("index: "+index);
                console.log("value: "+value);
                console.log(data.heights[i].index);
            });
        }

        $("#gallery").html(html);
    });
});

我也尝试过对这个console.log(data.heights[i].index);进行一些修改,但仍然没有可用的结果。

控制台输出

1
15

index: index1
value: /some/path
undefined

index: index2
value: /some/paht
undefined 

,JSON字符串看起来像这样

{
    "previews": [
        {
            "index1": "/some/path"
        },
        {
            "index2": "/some/path"
        }
    ],
    "heights": [
        {
            "index1": "67"
        },
        {
            "index2": "103"
        }
    ]
}

我将拥有更多具有相同索引的数组,因此如果可以在一个数组中解析它,那将会很棒。谢谢你的帮助

编辑:属性名称是动态的而不是静态的。它可以是任何东西,而不仅仅是index1,index2,......

1 个答案:

答案 0 :(得分:1)

当您使用.index时,您正在使用heights查看[index]数组中对象中的数据。所以这一行:

console.log(data.heights[i].index);

变为:

console.log(data.heights[i][index]);