2012-07-04 71 views
-5

我想將字符串從koderesult轉換成對象,然後obj.result應該是這樣>>obj.GetReportIdResult。 on函數detail(),koderesult是字符串,那麼我想用這個koderesult字符串作爲obj的對象。如何將koderesult字符串轉換爲對象名稱?
好,我有obj.GetReportIdResult得到JSON對象,那麼我想GetReportIdResult是DINAMIC(例如,它可以改變到GetReportMyResultGetReportHkResult) 這裏是我的功能:如何在屬性名稱位於變量中時檢索對象屬性?

function detail(kodenegara, koderesult) 
     { 
      $.ajax({ 
       type: "GET", 
       contentType: "application/json; charset=utf-8", 
       url: "http://10.80.3.73/webservice/Service1.svc/json/weeklyflash/"+kodenegara, 
       dataType: "json", 
       success:function(data){ 
        var json = JSON.stringify(data); 
        var obj = JSON.parse(json); 
        //alert (koderesult); 
        result = eval(koderesult); 
        alert(countTypesForBulan(obj.result, "4")); //this obj.result should be like this >> obj.GetReportIdResult 
       }, 
       error: function() { 
        alert("ERROR"); 
       } 
      }); 
     } 

這裏的按鈕來調用這個函數:

<button type="button" onclick="detail('id', 'GetReportIdResult')">Display JSON String</button> 
+4

不錯。它做什麼,你需要什麼......還沒有問題。 –

+0

你必須在服務器端 – coolguy

+0

上完成,在函數'detail()'上,'koderesult'是字符串,那麼我想爲'obj'對象使用這個'koderesult'字符串。如何將'koderesult'字符串轉換爲對象名稱? – blankon91

回答

1

你的問題不是很清楚。但我認爲你需要的是這樣的:

alert(countTypesForBulan(obj[koderesult], "4")); 

obj.GetReportIdResult一樣的是obj['GetReportIdResult']

+0

好吧,我有'obj.GetReportIdResult'來獲得JSON對象,那麼我想'GetReportIdResult'是動態的(例如它可以改爲'GetReportMyResult'或'GetReportHkResult') – blankon91

+0

@ blankon91 - 看起來'koderesult'是一個字符串,它將保存對象中屬性的名稱。如果是這樣,那麼'obj [koderesult]'(如xdazz的答案所示)就是你需要的。 '[]'語法使屬性名稱變爲動態 - 它從你的'koderesult'變量中獲取名稱。你不需要你的問題中的'result'變量或'eval'。 – nnnnnn

+0

更新:我添加'var result = koderesult;'現在它現在可以運行:))謝謝 – blankon91

相關問題