2016-09-09 11 views
1

내 json 응답에 대해 foreach하려고합니다.
이 내 JSON입니다 : AJAX의 성공에 따라서json 응답에 대한 Foreach

[ 
    { 
     "id":1, 
     "firstname":"Erich", 
     "sections":[ 
      "VIP Section", 
      "God Section" 
     ] 
    } 
] 

내가 할 :

$.each(data[0].sections[0] , function(i, star) { 
    $('#test-ul').append('<li>' + star + '</li>'); 
}); 

하지만 오류 받고 있어요 : 기록이 한 섹션 만있는 경우

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in VIP Section 
는, 그것의

오류를 반환하지 않지만 HTML에 추가하지는 않습니다.

답변

3

단어가 아닌 배열을 반복하는 것처럼 보입니다.

은 VIP 섹션 인 섹션의 0 요소에 액세스하고 그것을 반복하려고

$.each(data[0].sections , function(i, star) { 
    $('#test-ul').append('<li>' + star + '</li>'); 
}); 
0

개봉보십시오. 섹션에서 [0]을 제거하십시오.

0

"sections"속성은 문자열 배열이므로 구문 분석해야합니다.

<script> 
    var jsonData = [{ 
       "id": 1, 
       "firstname": "Erich", 
       "sections": [ 
        "VIP Section", 
        "God Section" 
       ] 
       }]; 
    function clickIt(){ 
    console.log(jsonData); 

    $.each(jsonData , function(i, star) { 
     console.log("id", star.id); 
     console.log("firstname", star.firstname); 
     console.log("sections"); 
     $.each(star.sections, function(i, sectionx){ 
     console.log(i, '-', sectionx); 
     }); 
    }); 
    } 

</script> 

enter image description here

:

은 JSON 결과를 구문 분석 아래의 코드를 사용하려고

관련 문제