2013-04-21 40 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]; 
    ... 
}