2012-02-14 44 views
0

我目前正在研究一個頁面,該頁面將讀取目錄(動態)中的XML文件,然後通過JSON將它們發送回客戶端。但是我不確定如何引用返回的JSON數組的動態元素。例如。

$.getJSON('getfilenames.php', function(data) { 
    for(var i in data) 
    { 
     var temp3 = data[i].name;(<-- if I dont know what .name was) 
     var temp2 = temp3.replace(".xml",""); 
     temp = temp +'<option value="'+temp3+'">' +temp2 +'</option>'; 
    } 
    temp = temp +'</select>'; 
    $("#div2").html(temp); 
} 

如果我還不知道什麼樣的數據中。名稱因素是,我怎麼可能: 答:檢索引用,或B它們的列表:訪問數據做我自己。 我也很好奇我如何從元素內部獲取元素。 EG:

{"contact":{"@attributes":{"id":"1"},"name":"John Doe","phone":"123-456-7890","address":"\n 123 JFKStreet\n "}} 

如何獲取名稱屬性。

回答

1

你只需要遍歷返回的對象的屬性..

for (var prop in data[i]){ 
    // prop hold the name of the property (name) in your example 
    // do something with data[i][prop] 
} 

你可以去爲與多個.符號的對象..

從您的最後一個例子(假設變量持有這個對象是data

data.contact.name // "John Doe" 
data.contact['@attributes'].id // 1 - we used the [] syntax because of @ 
+0

所以我會遍歷數據找到第一組元素,將它們保存到外部數組中,然後遍歷該aray(data.whateverelement [i]),直到找到數據爲止? – Fearlessunyielding 2012-02-14 01:25:23

+0

你可以創建一個處理單個級別的函數,並遞歸地使用它來讀取整個數據..但是如果你要使用除了在屏幕上轉儲它們的數據..你需要知道你在找什麼.. soome方法來識別你已經達到你想要的數據.. – 2012-02-14 01:28:41

+0

我只會需要去最多2個孩子,EG根,孩子的孩子。 (json直接來自xml文件),那麼這個約束就足以做2個嵌套的語句了嗎? – Fearlessunyielding 2012-02-14 01:37:14

相關問題