我搜索了我的问题,发现了很多我已经使用过的有用的东西。
这是计划:我想将 xml 文件中的数据加载到 javascript 变量中。读取 xml 数据的 DOMParser 函数将其推送到数组中,因此我可以稍后从数组中获取随机元素。
要了解我想要做什么:我想加载随机的 youtube 视频。视频的链接/结尾存储在 xml 文件中,如“d_HvwKtsy_Q”。视频结束后,它应该立即开始下一个。我已经想出了如何在 YT api 中执行此操作。我只需要将 xml 文件加载到变量中,这样我就可以在 extern xml 文件中对其进行编辑。
这是我到目前为止所得到的:
// This is my "xml file", but i want to have it in a extern file, so the variable
stores the extern xml file data like "externXMLfile.xml"
var xml_string ='<answers><answer id="0">o6f9wJ1DWhY</answer><answer id="1">72Y7M3_NlfI</answer></answers>'
function get_answers_from_xml_string(xml_string) {
// Parse the XML string into a XMLDocument
var doc = window.DOMParser
? new DOMParser().parseFromString(xml_string, 'text/xml') // Standard
: new ActiveXObject('Microsoft.XMLDOM').loadXML(xml_string); // IE
// Find the answer nodes
var answers_nodes = doc.getElementsByTagName('answer');
var answers = [];
// Loop through them and save their text content into an array
for (var i = 0; i < answers_nodes.length; i++) {
answers.push(answers_nodes[i].firstChild.data)
}
return answers;
}
//Save the xml elements in an array called answers
var answers = get_answers_from_xml_string(xml_string);
//This is the youtube api stuff, which works fine
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'd_HvwKtsy_Q',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
},
playerVars: {
'controls': 0,
'showinfo': 0,
'iv_load_policy': 3,
},
});
}
//this function loads a new random video id after the video stops from the array, which stores the xml elements
function getMessage() {
return answers[Math.floor(Math.random() * answers.length)];
}
function swapVideo() {
player.stopVideo();
player.loadVideoById(getMessage());
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
swapVideo();
}
}
我希望你能理解我的问题我想我几乎想出了一切,除了将 xml_string 变量与 extern xml 文件连接起来
感谢您的帮助!!