使用php-ajax更新另一个下拉列表的下拉列表

时间:2012-08-08 09:18:04

标签: php ajax

我想在国家/地区下拉列表中更改城市下拉列表的值。好吧,当我选择该国家的价值时,它已经停留在点,它表示变量$ r未定义。 页面:index.php

<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="150">Country</td>
    <td  width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
    <option value="">Select Country</option>
    <option value="1">USA</option>
    <option value="2">Canada</option>
        </select></td>
  </tr>
  <tr style="">
    <td>City</td>
    <td ><div id="citydiv"><select name="city">
    <option>Select City</option>
        </select></div></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

页面:findcity.php

<?php 
$country=$_REQUEST['country'];
$link = mysql_connect('localhost', 'root', ''); 
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="select city from city where countryid=$country";
$result=mysql_query($query);
?>
<select name="city">

<? while($r=mysql_fetch_array($result)) { 

?>
<option value=""><?php echo $r['city'];?></option>
<? } ?>
</select>

这是脚本

<script>
function getXMLHTTP() { //function to return the xml http object
        var xmlhttp=false;  
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {       
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }

        return xmlhttp;
    }



    function getCity(strURL) {      

        var req = getXMLHTTP();

        if (req) {

            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('citydiv').innerHTML=req.responseText;                      
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }

    }
</script>

3 个答案:

答案 0 :(得分:0)

尝试使用mysql_fetch_assoc代替mysql_fetch_array

答案 1 :(得分:0)

您错过了在<?(write down php here) while($r=mysql_fetch_array($result)) {附近写“php”。并执行一些调试,如检查您是否获得国家/地区的ID,而不是检查查询是否返回正确的结果或在浏览器上打印查询并在Database上运行该查询。

答案 2 :(得分:0)

将您的代码更改为..

<?php
  while($r=mysql_fetch_array($result))
  { 

      echo '<option value="">'.$r['city'].'</option>';
   } 
?>