0

我已经尝试过这个例子,但不确定我哪里出错了——我已经创建了数据库和相关字段。当我选择英国时,它给了我一个空白的结果。这是我的脚本

主文件

<?php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
$sql_country = "SELECT * FROM COUNTRY";
$result_country = mysql_query($sql_country) or die("Query problem");

echo "<form method='POST'>";
echo "<select name='country' onChange='get_cities(this.value)'>"; //get_cities is defined below
echo "<option value=''></option>";
while($row_country = mysql_fetch_array($result_country))
{
echo "<option value='".$row_country['id']."'>".$row_country['country']."</option>";
}
echo "</select>";

echo "<select name='city' id='city'></select>"; //We have given id to this dropdown
echo "</form>";
?>
<script type="text/javascript">
function get_cities(country_id)
{
$.ajax({
type: "POST",
url: "cities.php", /* The country id will be sent to this file */
beforeSend: function () {
$("#city").html("<option>Loading ...</option>");
},
data: "country_id="+country_id,
success: function(msg){
$("#city").html(msg);
}
});
}
</script>

城市.php

<?php
// Code for cities.php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
$country_id = $_REQUEST['country_id'];

$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
echo "<select name='city'>";

while($row_city = mysql_fetch_array($result_city))
{
echo "<option value='".$row_city['id']."'>".$row_city['city']."</option>";
}

echo "</select>";

?>

示例代码:http ://www.x-developer.com/php-scripts/loading-drop-downs-with-ajax-php-and-fetching-values-from-database-without-refreshing-the-page

4

5 回答 5

1

There doesn't seem to be any error checking in your example, and you should be aware that with databases, plenty of things can go wrong!

Try making these amendments. Change this:

$connect=mysql_connect("localhost","root","");

to:

$connect=mysql_connect("localhost","root","") or die("Cannot connect");

And this:

$result_country = mysql_query($sql_country);

to:

$result_country = mysql_query($sql_country) or die("Query problem");

This will highlight two common problems - connecting or not finding the specified table.


Also, cities.php doesn't appear to connect to the database at all. Add in the mysql_connect and the mysql_select_db from the first file into the second, and that should connect it correctly.


Lastly, there is a serious security vulnerability with this tutorial, which would permit internet users to run arbitrary SQL on your database server. Change this:

$country_id = $_REQUEST['country_id'];

to this:

$country_id = (int) $_REQUEST['country_id'];

That will force the country ID to be an integer, rather than just accepting it uncritically as a string.

于 2013-03-17T06:54:42.373 回答
0

您在 中没有任何数据库连接cities.php,因此SELECT语句不起作用。

于 2013-03-17T07:16:51.130 回答
0

The response from the server contains a dropdown menu, but the current code appends the HTML result not into a div or span, but into into another dropdown menu, thus:

<select name='city' id='city'><select name='city'>....</select> </select>

This is incorrect. To avoid this, change:

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

to

echo "<div id='city'> </div>";

Or, removeecho "<select>" line from cities.php

<?php
// DB CONNECTION
$country_id = $_REQUEST['country_id'];

$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);


while($row_city = mysql_fetch_array($result_city))
{
echo "<option value='".$row_city['id']."'>".$row_city['city']."</option>";
}



?>
于 2013-03-17T06:57:47.533 回答
0

如果您愿意使用 jquery,这对于 ajax 驱动的 Web 应用程序有很大帮助,请在您的 jquery 代码中试试这个

//ensure the select name 'country' has the id 'country'
$("#country").change(function(){
//get country id of the selected country option
var countryid = $("#country option:selected").val();
//here we post the id of the country to the php page. note that within the curly braces, the first parameter is what corresponds to the variable in php e.g $countryid=$_POST[country_id]. The second parameter is the javascript variable
$.post("cities.php",{country_id:countryid},function(data){
//check that the json object returned is not empty
if(!$.isEmptyObject(data))
       { 

     var html = '';
    var len = data.length;
    for (var i = 0; i< len; i++) {
        var cityid = [data[i].id];
        var cityname = [data[i].city];      
        html += '<option value = '+cityid+'>'+city+'</option>';

    }
//append the results of the query. The prepend part is to make a blank option first and make it selected so as to force a user to actually select a city.
       $("#city").html(html).prepend("<option value='' selected='selected'></option>").show();

        }   

        else{
             alert('No cities found for this country');
            }

},'json')
})

您的城市 php 页面保持原样,但进行以下调整

<?php
// Code for cities.php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
//change it from request to post.
$country_id = $_POST['country_id'];
//the below code is not safe!!! You are open to sql injection. To make it worse you are connected as root. A malicious user can drop your database. 
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);

while($row_city = mysql_fetch_array($result_city))
{
$data[] = $row_city;
}
//return the json onject to the client.
echo json_encode($data);

?>

如果您选择 jquery 编写 javascript 的方式,上面的代码可能会对您有所帮助。您需要先下载 jquery。

于 2013-03-17T08:25:25.210 回答
0

在您cities.php没有数据库连接。在那里也写数据库连接,然后它会给你下拉。

于 2013-03-17T06:59:30.200 回答