2010-01-07 2 views
0

아래와 같이 .replace()로 조작 된 리턴 된 JSON 데이터에 변수를 할당하는 방법. 목적 : JSON에서 반환 한 비디오 ID에서 비디오 미리보기 이미지의 URL을 작성하십시오.jQuery getJSON 결과에서 조작 된 데이터에 변수를 지정하십시오.

질문 : 썸네일 URL을 구성 할 수 있도록 변수에 비디오 ID (예 : mVWhWsWHzKM)를 할당하는 방법. http://i2.ytimg.com/vi/mVWhWsgHzKM/default.jpg하지만 난 그 코드를 실행하면, 그것은 원하는 결과를 렌더링하지 않습니다 다음의 img의 src URL처럼 보이는 결과

$.getJSON(
    'http://gdata.youtube.com/feeds/users/soccerdude1935/favorites?alt=json-in-script&callback=?', 
    function(data){ 
     $.each(data.feed.entry, function(i, item){ 
      // assign variable to the returned JSON data 
      var id = item['id']['$t']; 

      // URL contain video ID is put inside a P tag and assign class ID. 
      $("<p></p>").text(id).addClass('vidId'); 

      $('p.vidId').each(function() { 
       var id = $(this).text(); 
       // removes all other text from URL except for video ID. 
       id = id.replace("http://gdata.youtube.com/feeds/videos/",""); 
       // video ID is assigned to a var. Is this correct? because it is not working as a var. 
       // Note: no errors when running the code. 
       var imgSrc = $(this).text(id); 
      }); 

      // thumbnail URL construction and placement inside a img element's src tag. 
      $(<img />).attr('src', 'http://i2.ytimg.com/vi/'+imgSrc+'/default.jpg'); 
     }); 
    }); 

. 어떤 제안?

모든 아이디어는 크게 감사하겠습니다. 감사.

답변

1

코드를 제거하여 실제로 렌더링되도록했습니다. 방금 id = video로 div 태그를 만든 다음 각 축소판을 컨테이너에 추가했습니다.

코드를 사용하면 문제는 두 번째 각 문과 함께 나타납니다. 실행할 수 없으므로 imgSrc에 값을 할당하지 않습니다. 이제는 HTML이 없기 때문에 이것이 가능합니다.

<div id="video"></div> 
    <script> 
     $(document).ready(function() { 
      $.getJSON('http://gdata.youtube.com/feeds/users/soccerdude1935/favorites?alt=json-in-script&callback=?', 
      function(data){ 
       $.each(data.feed.entry, function(i, item){ 
        var id = item['id']['$t']; 

        id = id.replace("http://gdata.youtube.com/feeds/videos/",""); 

        $("#video").append('<div id="'+id+'">'); 
        $("#video").append('<img src="http://i2.ytimg.com/vi/'+id+'/default.jpg">'); 
        $("#video").append('</div>'); 
       }); 
      }); 
     }); 
    </script> 
+0

완벽하게 작동합니다. 고맙습니다! – Steve