HTML (index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-TW" xml:lang="zh-TW"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Jsonp dynamic</title> <script type="text/javascript"> function codeboxy(json) { document.getElementById("youtubeTitle").innerHTML = json.entry.title.$t; } function getYoutubeTitle() { var removeScript = document.getElementById('jsonScript'); if(removeScript) removeScript.parentNode.removeChild(removeScript); var yid = document.getElementById('yid').value; var script = document.createElement('script'); script.type = 'text/javascript'; script.id = 'jsonScript'; script.src = "http://gdata.youtube.com/feeds/api/videos/" + yid + "?alt=json-in-script&callback=codeboxy"; document.getElementsByTagName('head')[0].appendChild(script); } </script> </head> <body> <input type="text" id="yid" value="Sr3hyvjNp94" /> <input type="button" onClick="getYoutubeTitle()" value="Get" /> <div id="youtubeTitle"></div> </body> </html>範例:
說明:
使用純JavaScript動態在Head產生jsonp script後,呼叫函式更新Youtube之Title資料。
支援IE6、FireFox、Chrome。
沒有留言:
張貼留言