2013-10-04 23 views
0

我想解析包含少數數組和一些鍵值對的JSON字符串。我現在能夠從一個數組中獲取值,但我想從另一個數組中獲取值。數組有相同的鍵,但我不知道如何從第二個數組中獲取數據。使用jQuery從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" 
     } 
    ] 
} 

我將有更多的陣列,相同指數因此這將是巨大的,如果它會是可能的把它解析爲一個。感謝您的幫助

編輯:屬性的名稱是動態的而不是靜態的。它可以是任何,不只是索引1,索引2,...

回答

1

您正在使用.index當您應該使用[index]查找heights數組中的對象中的數據。所以這條線:

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

變爲:

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

謝謝!我會盡快接受你的回答。 – Jakolcz