简体   繁体   中英

Using button to retrieve data from XML

I have made a code in which on clicking computer Science button I get data from XML

<html>
<head>
<script src="loadxmldoc.js"></script>
 </script>
</head>
<body>
<h1 style="text-align:center">DEPARTMENT DETAILS</h1>
<button onclick="myfunction()">Computer Science</button>
</br>
<script>
function myfunction(){
xmlDoc=loadXMLDoc("faculty.xml");
var x=xmlDoc.getElementsByTagName("computer")[0];
var y=x.childNodes;
for(i=0;i<y.length;i++)
 document.write(y[i].nodeName+"&nbsp&nbsp"+y[i].childNodes[0].nodeValue+"</br>"); 
}
 </script>
  </body>
 </html>

When I click on button I do get the data but a new page is loaded. I would like to have data below the button. How to do so?

document.write is archaic and useful only before the DOM has loaded. If it's used after that, it overwrites the current DOM, as you've discovered.

Use DOM methods instead and prepare a container to receive the content.

HTML:

<div id='container'></div>

JS:

var cntr = document.querySelector('#container'), html = '';
for (var i = 0; i < y.length; i++) {
    html += y[i].nodeName+"&nbsp&nbsp"+y[i].childNodes[0].nodeValue+"</br>"; 
}
cntr.innerHTML = html;

Consider using this approach.

Basically load your xml data, and display the result in a div "result";

  <html>
    <head>
    <script src="loadxmldoc.js"></script>
     </script>
    </head>
    <body>
    <h1 style="text-align:center">DEPARTMENT DETAILS</h1>
    <button onclick="myfunction()">Computer Science</button>
    </br>
    <script>
    function myfunction(){
    xmlDoc=loadXMLDoc("faculty.xml");
    var x=xmlDoc.getElementsByTagName("computer")[0];
    var y=x.childNodes;
    var result = document.getElementById('result');
    for(i=0;i<y.length;i++)
    result.innerHTML = ''; // always reset
    result.innerHTML +='y[i].nodeName+"&nbsp&nbsp"+y[i].childNodes[0].nodeValue+"</br>"';
     //document.write(y[i].nodeName+"&nbsp&nbsp"+y[i].childNodes[0].nodeValue+"</br>"); 
    }
     </script>
     <div id="result"></div>
      </body>
     </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM