Javascript jQuery JSON未定义变量

Javascript jQuery JSON未定义变量,javascript,jquery,json,getjson,Javascript,Jquery,Json,Getjson,我的基本要求是,我可以获得youtube视频的标题,这样我就可以访问它并将其应用到我的页面,但是我遇到了一个问题,我试图在评论中解释这个问题: //first I declare my array and variable for the video information var videoID = []; var videoTitle; //this ensures that the <div> exists if ($("#productVideo0").length >

我的基本要求是,我可以获得youtube视频的标题,这样我就可以访问它并将其应用到我的页面,但是我遇到了一个问题,我试图在评论中解释这个问题:

//first I declare my array and variable for the video information
var videoID = [];
var videoTitle;

//this ensures that the <div> exists
if ($("#productVideo0").length > 0) {

    //then for every occurrence of and embedded video...
    $(".youtube-video").each(function () {

        //I call this function which strips the video id out of the URL (in the array[1] element]
        videoID = getVideoID($(this).children().attr('src'));

        //then I make the JSON call
        $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + videoID[1] + '?v=2&alt=jsonc', function (data) {

            //if I alert this line below, it displays the title. 
            //However, if I try to alert or use this variable outside the function 
            //it just displays "undefined" or [object,object] depending on what I do
            videoTitle = data.data.title;
        })

    })
}

//this uses regex to strip the id from the url
function getVideoID(url) {
    url = url.match(/embed\/(\w*)/);
    return url;
}
//首先声明视频信息的数组和变量
var videoID=[];
视频标题;
//这确保了
如果($(“#productVideo0”).length>0){
//然后对于每一个出现的视频和嵌入式视频。。。
$(“.youtube视频”)。每个(函数(){
//我调用这个函数,将视频id从URL中剥离出来(在数组[1]元素中)
videoID=getVideoID($(this.children().attr('src'));
//然后我进行JSON调用
$.getJSON('http://gdata.youtube.com/feeds/api/videos/“+videoID[1]+”?v=2&alt=jsonc',函数(数据){
//如果我在下面警告这一行,它将显示标题。
//但是,如果我尝试在函数外部警告或使用此变量
//它只显示“未定义”或[object,object],具体取决于我的操作
videoTitle=data.data.title;
})
})
}
//这将使用正则表达式从url中删除id
函数getVideoID(url){
url=url.match(/embed\/(\w*)/);
返回url;
}

为什么不尝试将所有data.data.title追加到列表中,而不是每次替换整个变量?也许上一次迭代将videoTitle变量设置为null

var videoID = [];
var videoTitle = [];

//this ensures that the <div> exists
if ($("#productVideo0").length > 0) {


    $(".youtube-video").each(function () {
        videoID = getVideoID($(this).children().attr('src'));

        //then I make the JSON call
        $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + videoID[1] + '?v=2&alt=jsonc', function (data) {


            videoTitle.push(data.data.title);
        })

    })
}
var videoID=[];
var videoTitle=[];
//这确保了
如果($(“#productVideo0”).length>0){
$(“.youtube视频”)。每个(函数(){
videoID=getVideoID($(this.children().attr('src'));
//然后我进行JSON调用
$.getJSON('http://gdata.youtube.com/feeds/api/videos/“+videoID[1]+”?v=2&alt=jsonc',函数(数据){
videoTitle.push(data.data.title);
})
})
}
函数$getJSON中定义了“data”json对象,一旦函数结束,对象将被销毁。
尝试在外部定义数据对象并通过引用getJSON将其发送。或者更好的做法是不要从外部调用它。

我真的看不到您在哪里解析JSON。使用控制台而不是警报,这样您就可以看到您的对象,而不是
[对象]