2012-12-19 173 views
0

我創建了一個使用PHP的網頁,並試圖根據用戶選擇加載XML文件。我看了各種網站和論壇,看看我是否做錯了什麼,但即使我嘗試複製代碼似乎並不工作。我得出的結論是,我需要一雙新的眼睛來注意我可能沒有的東西。當我從下拉列表中選擇一個項目時,我希望它加載選定的XML文件,並顯示其中的信息,但使用代碼我迄今爲止沒有任何事情發生。我從下拉列表中選擇一個選項,但沒有任何反應。我認爲這是加載XML文件的問題,因爲當我更改loadXML()函數中的代碼以輸出所選的選項時,它就起作用了。我只是不明白爲什麼它不起作用。任何幫助將不勝感激。PHP XML DOM - 加載XML文件

<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> 

回答

1

XML文件路徑設置不正確,嘗試

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

而且你有一個多行字符串,這將導致一個語法錯誤,更改

document.write(" 
    "); 

喜歡的東西

document.write("\n"); 

另外我們在加載頁面後會覆蓋整個頁面。

+0

進行了所有您指出的更改,但不幸的是它仍然無法正常工作! – 6TTW014

+0

@ Kimmy25你有什麼錯誤,如果你提醒(xhttp.status),你會得到什麼;'' – Musa