Working with Youtube Google API & jQuery
I'm iterating through each li that is generated by the db which produces a youtube link to the video I want to link to So essentially I have this:
<ul id="mediaList">
<li>
<p>http://www.youtube.com/watch?v=TOm-myVLmKU&l开发者_如何转开发t;/p>
</li>
<li>
<p>http://www.youtube.com/watch?v=odNde8wQ5uA</p>
</li>
</ul>
I need to iterate through each li item, grab the youtube link, grab the video id and then retrieve the JSON data and what the ultimate goal is, is to add an image tag of the thumbnail for that video into the list item for media list
To accomplish this I have this jquery code(Please note using no conflict so $ becomes $j):
$j(document).ready(function () {
$j("#mediaList li").each(function (){
var u = $j(this).find("p").text();
var reqStart = "http://gdata.youtube.com/feeds/api/videos/";
var reqSettings = "?v=2&alt=json-in-script&callback=?";
var vid = grabytvid(u);
var request = reqStart + vid + reqSettings;
$j.getJSON(request, function(data) {
var y = (data.entry["media$group"]["media$thumbnail"][0].url);
});
$j(this).append('<img src="' + y + '" alt="" />');
});
});
Where I'm making use of the Youtube API Feed call:
http://gdata.youtube.com/feeds/api/videos/[Video_ID_Here]?v=2
For your reference grabytvid is a function that just splits and grabs the video id:
function grabytvid(ystring)
{
var v = ystring.split("=").pop();
return v;
}
Are there any ideas where I'm going wrong here ?
It's simple. You y
isn't defined in $j(this).append('<img src="' + y + '" alt="" />');
as you set y
only inside the getJSON
function
I would do it this way
$("#mediaList li").each(function() {
var self = this, u = $(this).find("p").text();
var reqStart = "http://gdata.youtube.com/feeds/api/videos/";
var reqSettings = "?v=2&alt=json-in-script&callback=?";
var vid = grabytvid(u);
var request = reqStart + vid + reqSettings;
$.getJSON(request, function(data) {
var y = (data.entry["media$group"]["media$thumbnail"][0].url);
$(self).append('<img src="' + y + '" alt="" />');
});
});
Please note that y is not in-scope when you call it:
$j(this).append('<img src="' + y + '" alt="" />');
I recommend performing the following change:
var y;
$.getJSON(request, function(data) {
y = (data.entry["media$group"]["media$thumbnail"][0].url);
});
Hope this helps, Enjoy life.
精彩评论