i searched on my problem and found a lot of useful stuff which i already used.
This is the plan: I want to load data from an xml file into a javascript variable. A DOMParser function which reads the xml data pushes it into an array, so i can get random elements from the array later.
To understand what i want to do: I want to load random youtube videos. The links/endings of the videos are stored in the xml file like "d_HvwKtsy_Q". After a video ends it should start the next one right away. I already figured out how to do this in the YT api.. i just need to load the xml file into a variable, so i can edit it in a extern xml file.
This is what i´ve got so far:
// 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();
}
}
i hope you understand my problem i think i figured out almost everything but connecting the xml_string variable with the extern xml file
thanks for your help!!