愿和平与你同在 大家,我是使用 Ajax 的新手,问题是,我有 3 个下拉列表连接到数据库,第一个是"名称",第二个是"年龄",第三个是"国家"! 所以,我已经连接到数据库,并在第一个列表"name"中从中检索数据,然后使用 Ajax, 在选择第一个列表的任何选项并将它们放入名为"年龄"的第二个列表中后,我已经成功检索了匹配数据,问题是当我使用与第二个列表"年龄"完全相同的方式将匹配数据检索到第三个列表中称为"国家"它不起作用!所以请帮帮我,我正在使用这个例子来学习 Ajax,然后应用于一个更大的真实项目!这是代码:- 首先,主页.php页面:-
<?php
include "config.php";
?>
<html>
<head>
<script type="text/javascript">
function agematch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('age').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'connection.inc.php?name='+document.ajax.name.value, true );
xmlhttp.send();
}
function countrymatch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('country').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value, true );
xmlhttp.send();
}
</script>
</head>
<body>
<form id="ajax" name="ajax" >
Choose your name : <select name="name" id="name" select="selected" onchange="agematch();"> <option> </option>
<?php
$query = "SELECT DISTINCT name FROM info";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo"<option value ='".$row[0]."'> '".@$row[0]."'</option>";
}
?>
</select>
Age : <select id="age" name="age" onchange="countrymatch();"> </select>
country : <select id="country" name="country"> <option> </option> </select>
</form>
</body>
</html>
现在,第一个Ajax调用的页面:-
<?php
include "config.php";
echo " <option> </option> " ;
if(isset( $_GET['name']) ) {
@$name = $_GET['name'];
}
$query = "SELECT age FROM info WHERE name = '".@$name."' ";
$result = mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value ='".$query_row[0]."'> $query_row[0]</option> ";
}
?>
现在,随着第二个Ajax调用的页面,第三个下拉菜单:-
<?php
include "config.php";
if (isset( $_GET['age']) ) {
@$age=$_GET['age'];
}
$query = "SELECT country FROM info WHERE name='".@$name."' AND age='".@$age."' ";
$result= mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value = '".$query_row[0]."'> $query_row[0] </option> ";
}
?>
所以如您所见,这是代码,当然我通过一个名为"config.php"的页面连接到数据库,所以我希望您帮助我解决此问题并将数据库中的数据检索到第三个下拉列表中"国家"。提前感谢!
您在第二次调用中没有传递name
。
取代
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value, true );
跟
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value+'&name='+document.ajax.name.value, true );
希望有帮助。