1

我想在更改国家下拉列表时更改城市下拉列表的值。好吧,当我选择国家中的值时,现在卡在了点上,它说变量 $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>
4

3 回答 3

0

将您的代码更改为..

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

      echo '<option value="">'.$r['city'].'</option>';
   } 
?>
于 2013-01-09T21:13:57.393 回答
0

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

于 2012-08-08T09:47:28.933 回答
0

尝试使用mysql_fetch_assoc而不是mysql_fetch_array

于 2012-08-08T09:25:47.850 回答