Add javascript variable to javascript src?

后端 未结 5 808
暗喜
暗喜 2021-01-19 19:38

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

             


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-19 19:59

    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.

提交回复
热议问题