2011-03-28 99 views
2

我有一個接收JSON字符串的POST請求。字段,值或數組有多深?這些都是未知的。所以,我需要遍歷每個json值,它的索引和它的值,並根據它執行操作。通過動態JSON字符串循環訪問

$.post(
    "test.php", 
    { action: 'someaction', param: '2' }, 
    function(data) { 
     //now data is a json string 
     $.each(data, function() { 
     key = data.key; //i need to retrieve the key 
     value = data.value; //i need to retrieve the value also 

     //now below here, I want to perform action, based on the values i got as key and values 
     } 
    }, 
    "json" 
); 

我怎樣才能獲得JSON的值作爲分隔和keyvalue

回答

5

對不起,夥計們,但我自己解決了它。請不要生我的氣。 (如果它是由社會需要,我會刪除的問題。)

$.post(
    "test.php", 
    { action: 'someaction', param: '2' }, 
    function(data) { 
     //now data is a json string 
     $.each(data, function(key,value) { 
     alert(key+value); 
     //now below here, I want to perform action, based on the values i got as key and values 
     } 
    }, 
    "json" 
); 
+0

感謝張貼您的解決方案。你應該選擇這個答案。 – js1568 2011-03-28 19:33:02

2

好吧,JSON被解析成JavaScript對象。你可以使用for...in

for(var key in data) { 
    if(data.hasOwnProperty(key)) { 
     var value = data[key]; 
    } 
}