我是PHP和JavaScript的新手,我遇到了一个无法解决的编程问题,需要一些帮助。我有两个文件:
iisstart.htm
<html>
<head>
<script>
function showPrinters(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getprinters.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="printers" onchange="showPrinters(this.value)">
<option value="">Select a state:</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
<option value="HI">Hawaii</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="UT">Utah</option>
<option value="WA">Washington</option>
</select>
</form>
<br>
和另一个文件:getprinters.php
<!DOCTYPE html>
<html>
<body>
<?php
$q = strval($_GET['q']);
$con = new mysqli('localhost','root','w','w');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT DISTINCT City FROM Printers WHERE ST = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<select id='city' onchange='SelectCity()'>";
echo "<option value=''>Select Your City</option>";
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['City'] . "'>". $row['City']. "</option>";
}
echo "</select>";
mysqli_close($con);
?>
<script>
function SelectCity()
{
document.write("Hello");
}
</script>
</body>
</html>
问题在于:
当我直接运行getprinters.php时,我在选择选项(从MySQL数据库输出成功生成列表)中进行选择后,在网页上成功获得输出“Hello”。但是,当我运行调用getprinter.php的iisstart.htm并从选项列表中进行选择时,onchange ='SelectCity()'函数将不会运行 - 没有“Hello”输出。
我在网上做过一些研究,但仍然无法弄清楚。请您指出正确的方向来解决这个问题吗?
谢谢!
答案 0 :(得分:0)
将函数SelectCity()
从文件getprinters.php
替换为文件iisstart.htm
。从getprinters.php
删除HTML,脚本标记
<?php
$q = strval($_GET['q']);
$con = new mysqli('localhost','root','w','w');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT DISTINCT City FROM Printers WHERE ST = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<select id='city' onchange='SelectCity()'>";
echo "<option value=''>Select Your City</option>";
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['City'] . "'>". $row['City']. "</option>";
}
echo "</select>";
mysqli_close($con);
?>
同时将<div id="txtHint"></div>
添加到文件iisstart.htm