jquery ajax – 如何处理json响应

这是对我的ajax调用的响应。 我想处理每个数组元素来更新我的页面上具有Letter元素值的相应按钮的标题。 我需要更换警报(响应); 在json数组上有一个循环。

{ “列”:[ “PAGESNUM”, “LETTER”], “DATA”:[[ “372”, “A”],[ “922”, “B”],[ “779”, “C”], [ “3 78”, “d”],[ “132”, “E”],[ “353”, “F”],[ “551”, “G”],[ “591”, “H” ],[ “6”, “I”],[ “340”, “J”],[ “261”, “K”],[ “314”, “L”],[ “837”,” M “],[” 88″ , “N”],[ “120”, “O”],[ “303”, “P”],[ “14”, “Q”],[ “355” , “R”],[ “762”, “S”],[ “235”, “T”],[ “12”, “U”],[ “44”, “V”],[ “581” , “W”],[ “49”, “Y”],[ “19”, “Z”]]}

$.ajax({ type: "Get", url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json", data: "nbw=" + nbw, datatype: "html", success: function (response) { //usercount = parseInt(response.substring(0, 10)); ///$(_$this.target).attr('title', usercount); alert(response); }, error: function (xhr, textStatus, errorThrown) { alert('errorThrown'); } }); 

javascript是区分大小写的,所以你想要创建那个参数dataType ,如果你得到JSON,那么不要告诉jQuery你期待“html”

  dataType: "json", success: function (response) { alert(response.DATA[0][1]);//should alert "A" } 

如果需要进行一些循环,则数组是response.COLUMNSresponse.DATA (这是一个数组数组)。

 var numCols = response.COLUMNS.length; for( var i = 0; i < numCols; i++ ){ response.COLUMNS[i] } 

或循环嵌套数组

 var numData = response.DATA.length; for( var i = 0; i < numData; i++ ){ for( var j = 0; j < response.DATA[i].length; j++ ){ response.DATA[i][j] } } 

JSON输出中有许多数组。 例如,您可以遍历DATA属性,该属性是一个数组数组:

 success: function (response) { $.each(response.DATA, function(index, elements) { // for each element in the DATA array get the // coupes number and letter which are respectively the first // and second elements var number = elements[0]; var letter = elements[1]; ... }); }