【问题标题】:Placing a videoID in an iframe using AJAX使用 AJAX 在 iframe 中放置 videoID
【发布时间】:2019-03-22 01:37:40
【问题描述】:

我正在尝试通过 AJAX 显示来自我的播放列表之一的 YT 视频,但我无法用我获取的数据真正替换来自 iframe 的 videoID。

我这样获取数据:

const apiKey = 'MY_API_KEY'
const playlistId = "MY_PLAYLIST_ID"
const url = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=${playlistId}&key=${apiKey}`

const getData = function () {
 return fetch(url)
  	.then(response => response.json())
  	.then(data => {
    	return data.items.map(playlist => {
        return {
          videoId: playlist.snippet.resourceId.videoId
        }
      })
    })
}

现在我想测试是否可以将其中一个 videoId 放到我的 iframe 上,因此我尝试将其放入我的部分中,如下所示:

const playerTag = document.querySelector(".player")

const putVideoOn = function () {
  playerTag.innerHTML = ""
  playerTag.innerHTML = playerTag.innerHTML + `
		<div class="player-video">
			<iframe width="480" height="360" src="https://www.youtube.com/embed/${data.videoId}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
		</div>
	`
}

// then I ran the function on load

putVideoOn()

但我总是收到一条错误消息,提示我注入iframe 链接的变量未定义。

【问题讨论】:

  • 发布错误也非常有帮助。我确实注意到 const url 使用反引号而不是引号:url = `https:.. 而不是 url = 'https:..
  • 我不知道,YouTube 是否会允许您的计划。
  • 这是错误:Uncaught ReferenceError: data is not defined,然后当我使用${playlist.videoId} 时,我得到了Uncaught ReferenceError: playlist is not defined。当我尝试${videoId} 时,我得到了这个:Uncaught ReferenceError: videoId is not definedurl 有反引号,因为我在其中注入了两个 consts。当我运行 console.log 时,它会获取我想要的所有数据......

标签: javascript ajax youtube youtube-api youtube-data-api


【解决方案1】:

我在任何定义的地方都没有看到 data 变量:

const apiKey = 'MY_API_KEY'
const playlistId = "MY_PLAYLIST_ID"
const url = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=${playlistId}&key=${apiKey}`

您在putVideoOn 函数的URL 中使用${data.videoId},但我看不到data 变量的定义位置。

您只是在 getData 函数中使用它,如下所示:

return data.items.map(playlist => {
    return {
      videoId: playlist.snippet.resourceId.videoId
}

但您没有在变量data 中保存任何内容,因为它可能不存在

【讨论】:

  • 好电话...我尝试单独使用${playlist.videoId}${videoId},但我仍然遇到同样的错误。
  • 希望对你有用。有时(很多时候)我们会错过最明显的事情。如果您愿意,请接受我的回答 :) 祝您好运。
  • 这是错误:Uncaught ReferenceError: data is not defined Uncaught ReferenceError: playlist is not defined Uncaught ReferenceError: videoId is not defined 感谢您抽出宝贵时间回答我的问题!我会试试看的:)
  • 没问题。如果仍然产生相同的错误,请在 cmets 中告诉我。如果没有,请不要犹豫,开始一个新线程,我会留意的。
猜你喜欢
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 2011-06-11
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
相关资源
最近更新 更多