1

我正在尝试获取 youtube 视频的标题。所以我使用jQuery来解析json。但它是异步工​​作的,所以答案是在页面加载后出现的。结果是:

http://www.youtube.com/watch?v=Ym0hZG-zNOk(未定义)

我该如何解决?

谢谢。

http://jsfiddle.net/3vQht/

<html>

<head>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script>
        var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";

        var videoID = link.substring(link.indexOf("=") + 1, link.length);

        document.writeln("<a target='_blank' href='" + link + "'>" + link.bold() + "</a> (" + name(videoID) + ")<br>");

        function name(value) {
            var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc&callback=?";
            var fin;

            $.getJSON(source, function(json) {
                fin = json.data.title;
                console.log(fin);
            });

            return fin;
        }
    </script>
</head>

<body>
</body>

</html>
4

4 回答 4

3

嘿,
这是解决方案:)

<script type="text/javascript">
    function name(value) {
        var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc";
        $.ajax({
            type: 'GET',
            url: source,
            contentType: "application/json",
            dataType: 'json',
            success: function (json) {
                alert("here is the title: "+json.data.title+" .Use it how you want!");
            },
            error: function (e) {
                alert("error");
            }
        });
    }

    $(document).ready(function() {
        var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
        var videoID = link.substring(link.indexOf("=") + 1, link.length);
        name(videoID);
    });
</script>

如果您想获得数据同步,只需使用此版本:

 $.ajax({
            type: 'GET',
            url: source,
            async: false,
            contentType: "application/json",
            dataType: 'json',
            success: function (json) {
                alert("here is the title: "+json.data.title+" .Use it how you want!");
            },
            error: function (e) {
                alert("error");
            }
        });
    }
于 2012-12-01T23:06:28.533 回答
1

getJSON是异步的,所以当return fin;到达时,数据还没有被获取。

依赖于 JSON 的所有内容都必须在成功回调中。

于 2012-12-01T22:12:18.607 回答
0

如果您愿意,您还可以同步获取数据。检查参数的jQuery.ajax() 文档async

编辑:刚刚发现您正在使用 JSONP 加载数据,并且不可能同步执行此操作。您需要改用异步回调。

于 2012-12-01T22:35:53.880 回答
0

我没有玩过他们的api,但快速浏览一下

https://developers.google.com/youtube/2.0/developers_guide_json

表示它们支持 jsonp 回调,以便您可以预先添加一个将数据发送到回调函数的脚本(只需将 &callback=yourFunction 添加到 url 的末尾)

function prependScriptFromUrl(s){
  var a=document.createElement("script");
  var b=document.getElementsByTagName('head')[0];
  a.src=s;
  b.insertBefore(a,b.firstChild)
}
于 2012-12-01T22:53:40.973 回答