简体   繁体   中英

parse XML file with javascript in variable on click

I am trying to load a different xml file everytime a link is clicked, based on its href. I have the following in head:

JAVASCRIPT

window.onload=function() {
loadXMLDoc("papers.xml"); // loads the default xml file so that page is not empty
}

function scanForXML(){
var extLinks=document.getElementById('results_list').getElementsByTagName('a');
for (i=0; i<extLinks.length; i++) {
extLinks[i].onclick=function getName()
{
var fileName=this.getAttribute('href');
loadXMLDoc(fileName);
return false;
}
}
}

HTML

<ol id="results_list">
<li> <a class="tooltip" href="paper2.xml"> Teaching with Tablet PC's </a></li>
<li> <a href="paper3.xml" class="tooltip"> Tablet PC’s as Instructional Tools </a></li>
</ol>

The onclick event works, I get the href value but the new xmlFile does not get loaded. Any ideas why?

ps: no jquery plz, cannot use that. trying to learn better basic javascript

The Javascript load code - by the way it does not work in chrome and opera - but works the default xml file gets loaded in safari Code:

function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET",dname,false);
xmlhttp.send();
 xmlDoc=xmlhttp.responseXML;
}

Thanks! K

That's because the request is asynchronous : there is no response when your loadXMLDoc function returns.

The usual solution is this :

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState === 4) {
        if (xmlhttp.status === 200) {
                           // use xmlhttp.responseXML;
                    }
            }
   }
  xmlhttp.open("GET",dname,false);
  xmlhttp.send();

The main difference is that you don't use the return of the loadXMLDoc function but ask it to do something after it has fetched the XML.

Another solution would be to force a synchronous request using jquery's ajax function

EDIT : I mark it as duplicate as it's a frequent question but I hope this specific answer will help you.

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