Pergunta

I'm creating a web page that uses PHP and am trying to load an XML file depending on the users selection. I've had a look on various websites and forums to see if i'm doing something wrong but even if I try replicating the code it doesn't seem to work. I've come to the conclusion that I need a fresh pair of eyes to notice something that maybe I haven't. When I choose an item from the dropdown list I want it to load the selected XML file and display the information that is in it but with the code I have so far nothing at all happens. I select an option from the dropdown list and nothing happens. I think it's a problem with the loading of the XML file because when I changed the code in the loadXML() function to output the option chosen, it worked. I just can't figure out why it's not working. Any help would be greatly appreciated.

<html>
<head>
<h1><u>State Information</u></h1>
</head>
<body>
<p><b>Please select an area of the US in the dropdown list below.</b></p>
<p><select name="area" onchange="loadXML(this.value)">

<?php
//set directory and open it
$xmldir = 'XML';
$dir = opendir($xmldir);

//create array and read through files in directory
$xmlfiles = array();
while ($file = readdir($dir))
{
//if the first char is not '.' then add to array
if (substr($file,-1,1) !== ".")
{
    $xmlfiles[] = $file;
} else
{
    //do nothing
}
}

echo '<option value="select">Select</option>';

foreach($xmlfiles as $area){ 
      echo '<option value="'.$area.'">'.$area.'</option>'; 
}
echo '</select>';

//close directory
closedir($dir);
?>

</p>
</body>
</html>

<script>
function loadXML($area) {
if (window.XMLHttpRequest)
{
    xhttp=new XMLHttpRequest();
}
else
{
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",$area,false);
xhttp.send();
xmlDoc = xhttp.responseXML;
x=xmlDoc.getElementsByTagName("name");

for (i=0;i<x.length;i++)
        {
    document.write(x[i].childNodes[0].nodeValue);
    document.write("
       ");
} 
}
</script>
Foi útil?

Solução

Your xml file path isn't set correctly, try

echo '<option value="XML/'.$area.'">'.$area.'</option>'; 

Also you have a multiline string which will cause a syntax error, change

    document.write("
   ");

to something like

    document.write("\n");

Also using document.write after the page loads will overwrite the entire page.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top