2012-02-11 99 views
1

我想动态制作不同的YouTube JSON API请求,然后使用函数对我想要的数据进行排序。动态加载YouTube JSON API

当前遵循YouTube数据JSON API网站here上的示例。

这是我现在的代码,它很好地让我的id很好。 我的问题是目前它使用脚本标记和回调URL查询来使用我的功能。是否有另一种方法可以在JavaScript中实现,并继续执行调用getid函数的请求?

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Untitled Document</title> 
</head> 
<body> 
<script type="text/javascript"> 
function getid(data) { 
    var i=0; 
    for(items in data.data){ 
     i++ 
     console.log(data.data.items[i].id) 
    } 
} 
</script><script type="text/javascript" src="https://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc&callback=getid"></script> 
</body> 
</html> 

回答

1

jsonp功能下面将动态创建一个脚本标记,并将其追加到身体。

function jsonp(url,callback) {      
    var script = document.createElement("script");   
    script.setAttribute("src",url); 
    script.setAttribute("type","text/javascript");     
    document.body.appendChild(script); 
} 

function getid(data) { 
    var i=0; 

    for(items in data.data){ 
    i++ 
    console.log(data.data.items[i].id) 
    } 
} 

// pass a url and callback 
var url = "https://gdata.youtube.com/feeds/api/videos?q=surfing&v=2&alt=jsonc&callback=getid"; 
jsonp(url, getid)