2013-04-21 41 views
1

Spring正在返回一個帶有四個屬性的json編碼對象。其中之一是名爲「數組」的屬性。我想要這個數組的內容。Javascript:麻煩分析json響應

這裏是整個JSON響應:

ee 
{"map":null,"array":[{"id":2,"description":"Cloud For Dev","businessSize":2,"businessType":9,"businessLocation":3},{"id":3,"description":"Cloud For Prod","businessSize":2,"businessType":9,"businessLocation":3}],"string":null,"bool":false} 
0 

我實際上並不知道什麼是「EE」或0的意思是......反正,我試圖分析它是這樣的:

$.ajax({ 
    type: "GET", 
    url: "/ajax/rest/teamService/list", 
    dataType: "json", 
    success: function (response) { 
     var teamArray = response.array; 

     var $el = $("#teamSelect"); 
     $el.empty(); 

     $.each(teamArray[0], function(team) { 
       alert(team.description); 
       $el.append($("<option></option>").attr("value", team.id).text(team.description)); 
     }); 

     // Reattach the plugin 
     $("#teamSelect").selectbox("detach"); 
     $("#teamSelect").selectbox("attach"); 
    }, 
    error: function (jqXHR, textStatus, errorThrown) { 
     if (textStatus === 'error') { 
      setTimeout(function() { window.location = '/do/login'; }, 7000); 
     } 
    } 
}); 

我得到彈出框6次(應該是2),每次它說「未定義」,而不是實際的描述。

選擇框本身有四個空白選項。

好像我遍歷json編碼對象的四個參數,而不是封閉數組的兩個內容。

我該如何解決這個問題?

+3

這根本不是一個有效的JSON字符串。那些「ee」和0表示語法和響應無法解析。 – MaxArt 2013-04-21 18:07:33

+0

我也懷疑這兩個位。我看到他們在提琴手顯示的JSON響應,我不確定他們的意思。 – Lurk21 2013-04-21 18:16:01

回答

1

試試這個 - teamArray[0]應該只有teamArray

$.each(teamArray, function(i,team) { 
    alert(team.description); 
    $el.append($("<option></option>").attr("value", team.id).text(team.description)); 
}); 
+0

這會導致它彈出未定義兩次,這是正確的次數。 team.description和team.id爲空。如此接近,但尚未正確。 – Lurk21 2013-04-21 18:14:48

+0

嘗試'alert(this.description);',http://jsfiddle.net/mohammadAdil/4uZbE/ – 2013-04-21 18:19:51

+0

返回正確的數據。問題解決了,但爲什麼'這個'而不是'團隊'? – Lurk21 2013-04-21 18:23:23

0

現在,你遍歷的teamArray[0]的鑰匙,因此六個警報。循環播放teamArray。另外,$.each的回調takes indexInArray, valueOfElement。也可以不通過jQuery:

for(var i = 0; i < teamArray.length; i++) { 
    var team = teamArray[i]; 
    ... 
}