【问题标题】:jQuery JSON not defining variables [duplicate]jQuery JSON没有定义变量[重复]
【发布时间】:2014-01-20 13:58:05
【问题描述】:

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

//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;
}

【问题讨论】:

  • 我看不出你在哪里解析 JSON。
  • 使用控制台代替警报,然后您将能够看到您的对象而不是[object Object]

标签: javascript jquery json getjson


【解决方案1】:

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

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);
        })

    })
}

【讨论】:

    【解决方案2】:

    “data”json 对象在函数 $.getJSON 中定义,一旦函数结束,对象将被销毁。 尝试在外部定义数据对象并通过引用 getJSON 来发送它。或者更好,但不要从外部调用它。

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2021-04-10
      相关资源
      最近更新 更多