2013-07-15 7 views
0
{ 
"entries": [ 
    { 
     "id": 23931763, 
     "url": "http://www.dailymile.com/entries/23931763", 
     "at": "2013-07-15T21:05:39Z", 
     "message": "I ran 3 miles and walked 2 miles today.", 
     "comments": [], 
     "likes": [], 
     "user": { 
      "username": "DeanaLaughli", 
      "display_name": "Deana O.", 
      "photo_url": "http://s3.dmimg.com/pictures/users/361413/1329826045_avatar.jpg", 
      "url": "http://www.dailymile.com/people/DeanaLaughli" 
     }, 
     "workout": { 
      "activity_type": "Fitness", 
      "distance": { 
       "value": 5, 
       "units": "miles" 
      }, 
      "felt": "great" 
     } 
    }, 
    { 
     "id": 23931680, 
     "url": "http://www.dailymile.com/entries/23931680", 
     "at": "2013-07-15T21:01:03Z", 
     "message": "More strength training", 
     "comments": [], 
     "likes": [], 
     "location": { 
      "name": "MA" 
     }, 
     "user": { 
      "username": "Ecm2571", 
      "display_name": "Eileen", 
      "photo_url": "http://s3.dmimg.com/pictures/users/323833/1368556483_avatar.jpg", 
      "url": "http://www.dailymile.com/people/Ecm2571" 
     }, 
     "workout": { 
      "activity_type": "Weights", 
      "title": "Upper and lower body " 
     } 
    } 
] 
} 

다음은 URL에서 JSONP 요청을 통해 얻는 JSON 배열의 예입니다.JSON Array - 데이터 표시에 도움이 필요합니다.

  • PHOTO_URL
  • 이름
  • 메시지
  • location.name
  • workout.activity_type
  • workout.duration
  • workout.distance.value
  • : 나는 디스플레이에 노력하고 있습니다 workout.distance.units

그러나 배열에서 볼 수 있듯이이 정보는 제공되지 않으며 때때로이 코드가 더 많은 항목을로드하는 것을 중지합니다. 로드 할 데이터가 없을 때 공백을 표시하는 방법이 필요합니다. 여기 내 코드, 어떤 도움을 주셔서 감사합니다.

<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script> 
<script> 

$(function() { 

var entries = []; 
var workout.activity 
var dmJSON = "http://api.dailymile.com/entries.json?callback=?"; 
$.getJSON(dmJSON, function(data) { 
$.each(data.entries, function(i, f) { 
    var tblRow =  "<tr>" + 
      "<td><img src=" + f.user.photo_url + "></td>" + 
      "<td>" + f.user.username + "</td>" + 
      "<td>" + f.message + "</td>" + 
      //"<td>" + f.location.name + "</td>" + 
      "<td>" + f.workout.activity_type + "</td>" + 
      "<td>" + f.workout.duration + "</td>" + 
      "<td>" + f.workout.distance.value + f.workout.distance.units + "</td>" + 
      "</tr>" 
    $(tblRow).appendTo("#entrydata tbody"); 
}); 

}); 

}); 
</script> 
</head> 

<body> 

<div class="wrapper"> 
<div class="profile"> 
<table id= "entrydata" border="1"> 
<thead> 
     <th></th> 
     <th>Username</th> 
     <th>Message</th> 
    <th>Exercise Type</th> 
    <th>Duration</th> 
    <th>Distance</th> 
    </thead> 
    <tbody> 

    </tbody> 
</table> 

</div> 
</div> 

</body> 

</html> 
+1

당신이 오류를 얻을 것이다. * 무엇이 잘못되었는지를 판별하려면 오류 콘솔을 읽으십시오 *. 경비원이나 감시단을 세우거나 "경로 평가자"를 사용하십시오. – user2246674

+3

삼항 연산자가있는 간단한 가드 :'f.workout.distance? f.workout.distance.value + f.workout.distance.units : ""'-하지만 사소한 일이라면 큰 문맥을 고려하여 (예 : 마지막 td 표시하지 않음) 더 잘 작성해야합니다. – user2246674

+0

값을 공백으로 초기화/설정하는 방법이 있습니까? 데이터가 배열에없는 경우 공백으로 표시됩니까? – Maggy

답변

2

먼저 크롬으로 실행하고 웹 도구를 엽니 다. "도달"오류가 발생하면 콘솔 로그에 오류가 표시됩니다.

당신이 읽으려고하는 정의되지 않은 값이 있다는 것입니다. 값 형식을 읽으 려하기 전에 각 개체를 확인하거나 값이 누락 될 때마다 기본값을 반환하는 함수를 사용하여 해결할 수 있습니다.

여기 당신을 위해 전체 작업 코드입니다 (이것은 2 응답 있기 때문에) f.workout.distance`가 정의되지 않은 경우 '

<!DOCTYPE html> 
<html> 
<head> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
    <script> 

     /** 
     * Extract the property formthe object. 
     * If teh property not found it will return empty string 
     */ 
     function getProperty(object, property) { 

      if (!property) { 
       return ''; 
      } 

      var 
      // Break the property to its nested properties 
        properties = property && property.split('.'), 
      // the current object that we want to extract the property from 
        current = object, 
        index; 

      // Loop over the properties and process them 
      for (index = 0; index < properties.length; index++) { 
       property = properties[index]; 
       // Check to see that there is a property with the given name 
       if (current.hasOwnProperty(property)) { 
        current = current[property]; 
       } else { 
        return '... N/A ...'; 
       } 
      } 

      // If we got so far it means the the 'current' contain the needed value 
      return current; 
     } 

     $(function() { 

      var entries = [], 
        dmJSON = "http://api.dailymile.com/entries.json?callback=?"; 

      $.getJSON(dmJSON, function (data) { 
       $.each(data.entries, function (i, f) { 
        var tblRow = "<tr>" + 
          "<td><img src=" + getProperty(f, 'user.photo_url') + "></td>" + 
          "<td>" + getProperty(f, 'user.username') + "</td>" + 
          "<td>" + getProperty(f, 'message') + "</td>" + 
         //"<td>" + f.location.name + "</td>" + 
          "<td>" + getProperty(f, 'workout.activity_type') + "</td>" + 
          "<td>" + getProperty(f, 'workout.duration') + "</td>" + 
          "<td>" + getProperty(f, 'workout.distance.value') + getProperty(f, 'workout.distance.units') + "</td>" + 
          "</tr>"; 

        $(tblRow).appendTo("#entrydata tbody"); 
       }); 

      }); 

     }); 
    </script> 
</head> 

<body> 

<div class="wrapper"> 
    <div class="profile"> 
     <table id="entrydata" border="1"> 
      <thead> 
      <th></th> 
      <th>Username</th> 
      <th>Message</th> 
      <th>Exercise Type</th> 
      <th>Duration</th> 
      <th>Distance</th> 
      </thead> 
      <tbody> 

      </tbody> 
     </table> 

    </div> 
</div> 

</body> 

</html> 
+0

훌륭하지만이 결론에 도달하는 방법을 정확히 알지 못해서 이것이 나에게 매우 도움이된다. – Maggy

관련 문제