3

我想为我的动态选择城市列表找到解决方案,现在我已成功填充城市,但现在无法将所选城市发布到数据库。

这是php文件:

<html>
<head>
<script type="text/javascript" src="show_cities.js"> </script> 
</head>
<body>
<?php 
session_start;
//library   
include("conn.php");
?>
<form enctype='multipart/form-data' action='posting_process.php' method='post'>");
<!-- **************************** Country select list ********************** -->
Country: 
<select name="country" onChange="showCities(this.value)">
<?php $sql = 'SELECT country_no, country_name FROM country '.'ORDER BY country_no';
    $rs = mysql_query($sql);
    echo "<option value='0'>"."Select a Country"."</option>\n  ";
    while($row = mysql_fetch_array($rs))
    {
echo "<option value=\"".$row['country_no']."\">".$row['country_name']."</option>\n  ";
    }
?>
</select>
City: <div id="txtCity" class="city_no">
<input type=submit name=action value=Post>
</body>
</html>

这是javascript:show_cities.js

// JavaScript Document
/* <script type="text/javascript"> */
function showCities(str)
{
if (str=="")
{
document.getElementById("txtHint").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("txtCity").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_cities.php?q="+str,true);
xmlhttp.send();
}
/* </script> */

这是 php 文件:get_cities.php

<?php
session_start;
//library   
include("conn.php");
$q=$_GET["q"];

$sql="SELECT * FROM city WHERE country_no = ".$q;
$result = mysql_query($sql);

echo "<select name='city'>";

while($row = mysql_fetch_array($result))
{

echo "<option value=\"".$row['city_no']."\">".$row['city_name'] . "</option>\n";
}
echo "</select>";

?>

我不知道如何提及以下返回/显示城市的内容:

4

1 回答 1

0

为什么不使用 jQuery Ajax 将数据发送到后端 php 代码并接收响应。您的 php 代码看起来不错,我建议使用以下机制来处理 ajax。

请在前端 html 页面中将 id 作为“countrylist”添加到您的国家/地区列表中。

并使用以下代码而不是您的 javascript 进行 ajax 调用。

$(function (){
    $('#countrylist').change(function() {
        var sel_val=$("#countrylist").val();
        $.ajax({
           url: 'get_cities.php?q='+sel_val,
           success: function(data) {
             $('#txtCity').html(data);
           }
        });
    });
});

还要确保在添加此 javascript 代码之前添加了 jquery 库。

希望这可以帮助。

谢谢

于 2012-08-15T04:38:10.517 回答