1

Currently fetching the first video from a search on YouTube using the code below, but when docready is called, the ids are not set. The code does not wait for the ajax results to be returned, instead it continues and returns nothing.

I've tried the async:false with the ajax thinking it might make it 'wait' but still nothing is returned. How would I fix this so all the ids will be set?

$(document).ready(function () {
    docready();
});

function docready() {
    var id1 = grabid("cat");
    var id2 = grabid("dog");
    var id3 = grabid("goldfish");
    alert(id1);
}

function grabid(keyword) {
    var url = 'http://gdata.youtube.com/feeds/api/videos?q=' + encodeURIComponent(keyword) + '&format=5&max-results=1&v=2&alt=jsonc';
    $.ajax({
        async: false,
        type: "GET",
        url: url,
        dataType: "jsonp",
        success: function (responseData, textStatus, XMLHttpRequest) {
            if (responseData.data.items) {
                var videos = responseData.data.items;
                videoid = videos[0].id;
                alert(videoid);
                return videoid;
            }
        }
    });
}

UPDATE: I've just changed the code above a bit to make my problem a bit clearer. When the code is run it alert's the real 'videoid' 3 times as expected. But when it gets to alert(id1) it returns undefined - so the 'return videoid' is ignored and not passing it back to the variable.

UPDATE 2 STILL UNSOLVED

4

4 回答 4

0

首先你的ajax调用有问题试试这个..

 $.ajax({
     type: "GET",
     url: url,
     dataType: "jsonp",
     success: function (responseData) {
                  var videos = responseData.data.items;
                  var videoid=videos[0].id;
                   alert(videoid);
                  //pass this videoid to anyother JS function it should work
                },
     error: function (xhr, textStatus, XMLHttpRequest) {
                 alert(xhr.responseText);
                }   

 });

编辑:

更新代码以从 ajax 调用返回:

 function grabid(keyword){
   var url = 'http://gdata.youtube.com/feeds/api/videos?q='+encodeURIComponent(keyword)+'&format=5&max-results=1&v=2&alt=jsonc';
  return $.ajax({
     type: "GET",
     url: url,
     dataType: "jsonp"       
    });   

}



function getVideoId(key) {
  key.success(function(respdata) {
      var videos = respdata.data.items;
      var videoid=videos[0].id;
     alert(videoid)
   });
  }

var ids = grabid(123);
getVideoId(ids);

删除所有加载或文档准备功能,这应该可以工作。

编辑 :

你唯一能做的就是做 async:false,它会等待 ajax 调用完成并返回一个值......但是 CROSS DOMAIN 调用不是同步的,所以我可以说你不走运.. 你需要重新想想ajax调用的逻辑。

同样从 jQuery 1.8 开始,不推荐使用 async: false 。

于 2012-07-14T15:41:58.270 回答
0

我已经成功使用了以下(警告:剥离了一堆其他代码,所以这可能不会按原样运行)

function getVideos(playlistID) {
                $.ajax({
                    type: 'GET',
                    url: "http://gdata.youtube.com/feeds/api/playlists/" + playlistID + "?v=2&alt=json",
                    crossDomain: true,
                    processData: true,
                    data: {},
                    dataType: "jsonp",
                    success: loadVideos
                });
}

function loadVideos (data) {

        if (data && data.feed && data.feed.entry) {
            var markup = '<ul>';
            $.each(data.feed.entry, function (index) {
                var url = 'http://www.youtube.com/embed/' + this.media$group.yt$videoid.$t + '?rel=0&wmode=transparent',
                    title = this.title.$t,
                    thumb = this.media$group.media$thumbnail[0].url;
                markup += "<li><a data-rel='videos' href='" + url + "' target='_blank' class='youtube' title='" + title + "'><img src='" + thumb + "' alt='" + title + "' /></a></li>";
            });
            markup += '</ul>';


    }
于 2012-07-14T18:21:19.593 回答
0

好的,这就是我尝试过的似乎有效的方法

function grabid(query) {
var yurl ='http://gdata.youtube.com/feeds/api/videos';
yurl = yurl+'?key=<GDATA API KEY>';
yurl = yurl+'&orderby=relevance';
yurl = yurl+'&start-index=1';
yurl = yurl+'&max-results=1';
yurl = yurl+'&v=2';
yurl = yurl+'&q='+encodeURI(query);

$.ajax({
    async: false,
    type: "GET",
    url: yurl,
    dataType: "xml",
    success: parseXml
});

var ytvideo = {
    ttl:title,
    vid:videoid,
    thm:thumb,
    vws:views,
    dur:duration
}
return ytvideo;
}

function parseXml(xml) {
$(xml).find("entry").each(function() {
    title = $(this).find("title").text();
    thumb = $(this).find("media\\:thumbnail, thumbnail").attr("url");
    videoid = $(this).find("yt\\:videoid, videoid").text();
    duration = $(this).find("yt\\:duration, duration").attr("seconds");
    views = $(this).find("yt\\:statistics, statistics").attr("viewCount");
});
}
于 2013-11-19T09:36:44.457 回答
-1

您的问题是函数范围,您的 ajax 回调函数返回到什么?它不是你认为它可能在的地方。为什么不在所有函数的范围内创建一个数组并将 id 分配给它。下面的示例(未经测试)

// Id array in scope of all functions in this script
var id = [];

$(document).ready(function () {
    docready();
});

function docready() {
    // Removed vars as all id's are in the id array. Just grab what you want
    grabid("cat");
    grabid("dog");
    grabid("goldfish");

    // Alert the 'cat' item in the id array
    alert(id['cat']);
}

function grabid(keyword, success_callback) {
    var url = 'http://gdata.youtube.com/feeds/api/videos?q=' + encodeURIComponent(keyword) + '&format=5&max-results=1&v=2&alt=jsonc';
    $.ajax({
    async: false,
    type: "GET",
    url: url,
    dataType: "jsonp",
    success: function (responseData, textStatus, XMLHttpRequest) {
        if (responseData.data.items) {
            var videos = responseData.data.items;

            // Assign the video ID for the keyword to (array)id
            id[keyword] = videos[0].id;
        }
    }
});
于 2012-07-14T16:10:43.793 回答