views:

323

answers:

1

How to assign a variable to returned JSON data that has been manipulated with .replace() as shown below. Purpose: build the URL for the video thumbnail image from video ID returned by JSON.

Question: How to assign a video ID (ex. mVWhWsgHzKM) to a variable so thumbnail URL can be constructed.

$.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');
        });
    }); 

resulting in the img src URL looking like: http://i2.ytimg.com/vi/mVWhWsgHzKM/default.jpg but when I run that code, it does not render the desired results. Any suggestions?

Any ideas would be greatly appreciated. Thanks.

+1  A: 

I stripped down the code to actually get it to render. I just created a div tag with the id=video and then just appended each thumbnail to the container.

Using your code, it appears the problem is with your second each statement. It's failing to run and so it never assigns a value to imgSrc. Now this could be because I don't have the HTML.

    <div id="video"></div>
    <script>
        $(document).ready(function () {
            $.getJSON('http://gdata.youtube.com/feeds/users/soccerdude1935/favorites?alt=json-in-script&amp;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"&gt;');
                    $("#video").append('</div>');
                });
            }); 
        });
    </script>
Scott Gottreu
Works perfectly. Thank you!