我想从XML文件中获取数据以显示在通过单击按钮获得的html页面中。单击该按钮后,我希望它选择一个随机子级,并显示子级数据。我制作了一个XML文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
 <kdramas>
  <kdrama>
    <title lang="en">A Gentleman's Dignity</title>
    <genre>Comedy, Romance, Drama</genre>
    <year>2012</year>
    <episodes>20</episodes>
    <about>This drama will tell the story of four men in their forties as they go through love, breakup, success and failure. </about>
</kdrama>
<kdrama>
    <title lang="en">Boys Over Flowers</title>
    <genre>Comedy, Romance, Drama, School</genre>
    <year>2009</year>
    <episodes>25</episodes>
    <about>about text</about>
</kdrama>
<kdrama>
    <title lang="en">Goblin</title>
    <genre>Comedy, Romance, Melodrama, Supernatural</genre>
    <year>2016</year>
    <episodes>16</episodes>
    <about>about text</about>
</kdrama>




单击按钮时,我可以显示XML数据,但是它显示了所有数据(标题除外)。我环顾四周,看看是否有可能选择一个随机子项然后显示其子子项元素,但是到目前为止,我没有任何运气。我必须显示XML数据的JS代码是:

function getDrama(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("content").innerHTML =
    this.responseText;
    document.getElementById("content").style.display = "block";
  }
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}


有关如何执行此操作的任何想法?甚至只是将我指向一个可以自己阅读如何做的地方也很棒吗?

最佳答案

使用JQuery结构$(_ your_text _)。find('_ elenent_name_')查找数据:



function getDrama(_callback){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    //document.getElementById("content").innerHTML = this.responseText;
    //document.getElementById("content").style.display = "block";
    _callback(this.responseText);
  }
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}

function get_random_title(){
   getDrama(function(_text){
   	  var titles_length = $(_text).find('kdrama').length;
   	  var random_number = 1 + Math.floor(Math.random() * titles_length);
   	  var random_title = $(_text).find('kdrama').eq(random_number).find('title').text();
	  $('#content').html( random_title );
   });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


  <div id="content"></div>


  <input type="button" value="Get Random Title" onClick="get_random_title();">

09-21 00:01