我有一个组合框,我想填写状态和Zip_code字段..工作但它填充每个字段状态“NY11715”和Zip_code“NY11715”...我想填写状态“NY”和Zip_code 11715 ...请帮我解决这个问题
<select name="LookupCity" id="LookupCity" onchange="showZip(this.value)">
<option value="" <?php if (!(strcmp("", $_GET['City']))) {echo "selected=\"selected\"";} ?>>Select from menu</option>
<?php do { ?>
<option value="<?php echo $row_fmCity['City']?>"<?php if (!(strcmp($row_fmCity['City'], $_GET['City']))) {echo "selected=\"selected\"";} ?>><?php echo $row_fmCity['City']?></option>
<?php
} while ($row_fmCity = mysql_fetch_assoc($fmCity));
$rows = mysql_num_rows($fmCity);
if($rows > 0) {
mysql_data_seek($fmCity, 0);
$row_fmCity = mysql_fetch_assoc($fmCity); } ?> </select>
<a href="ZipLookup.php">select</a></td>
</tr><tr valign="baseline">
<td nowrap="nowrap" align="right">State:</td>
<td><input type="text" name="State" id="State" placeholder="NY" value="<?php echo $_GET['State']; ?>" size="5"/>
<input type="text" name="Zip_Code" id="Zip_Code"placeholder="zip code" value="<?php echo $_GET['Zip']; ?>" size="10" /></td>
Ajax code
function showZip(str)
{
if (str=="")
{
document.getElementById("State").innerHTML="";
document.getElementById("Zip_Code").innerHTML="";
return;
}
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("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Getzip.php?q="+str,true);
xmlhttp.send();
}
PHP Code
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Leadbook", $con);
$sql="SELECT * FROM Zip WHERE City = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$State = $row['State'];
$Zip_Code = $row['Zip Code'];
}
echo $State;
echo $Zip_Code;
mysql_close($con);
?>
答案 0 :(得分:3)
<强> 1。更改您的PHP代码,以便城市和邮政编码都以逗号分隔。
更改此代码:
echo $State;
echo $Zip_Code;
到此:
echo $State;
echo ",";
echo $Zip_Code;
<强> 2。而不是更新你的javascript,以便将返回文本分成两部分并进入其受尊重的字段。
更改此代码:
document.getElementById("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
到此:
var string = xmlhttp.responseText;
var array = string.split(',');
document.getElementById("State").value=array[0];
document.getElementById("Zip_Code").value=array[1];
这应该按照你的要求做。