this may sound a bit noobish, but I'm trying to retrieve the video information for a YouTube video (I saw in some tutorial) basically here's the code
function youtubeFeedCallback1(data) {
var s = '';
var k = '';
s += data.entry.title.$t;
k += data.entry.media$group.media$thumbnail[2].url;
vidtitle1=s
vidthumb1=k
}
<script type="text/javascript" id="javaone" src='http://gdata.youtube.com/feeds/api/videos/'+vidid[0]+'?v=2&alt=json-in-script&callback=youtubeFeedCallback1' ></script>
As you can see, I'm trying to insert the var "vidid[0]" in the src, which doesnt work. Now, I did do my homework, but when i set a new script attribute and set the new src tot that it still does not work. Can anyone help me here?
What you're trying to do is called called JSONP. Since you can't use a regular Ajax call to fetch JSON from another domain (it would have security implications), you have to add a script that will call the callback function you specify, and pass it the JSON. As other answers say, you have to create the script tag programmatically. I wouldn't use document.write
for that, because it won't work after page load (the new script would replace the whole document). But there is a very simple alternative:
function youtubeFeedCallback1(data) {
var s = '';
var k = '';
s += data.entry.title.$t;
k += data.entry.media$group.media$thumbnail[2].url;
vidtitle1=s;
vidthumb1=k;
}
var script = document.createElement('script');
script.src = "http://gdata.youtube.com/feeds/api/videos/" + vidid[0] + "?v=2&alt=json-in-script&callback=youtubeFeedCallback1";
document.body.appendChild(script);
One last recommendation: I see you have global variables on your callback, vidtitle1
and vidthumb1
. Whatever you need to do with their values, do it from the callback (and preferably get rid of the global variables), or chances are it won't work. The data will be loaded asynchronously, so the variables are only guaranteed to contain their values after the callback runs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With