在我的网页上,我有两个下拉菜单。一个是国家列表,另一个是城市列表。国家/地区菜单中填充了数据库中的数据。选择其中一个国家/地区后,将通过php文件(getdata.php)填充以下下拉列表,该文件将选择国家/地区值并使用数据库查询并将城市名称回显到下拉列表中。我正在努力解决的问题是,当选择一个城市时,我如何获取城市选择的文本并在另一个php(displayCity.php)中使用此文本来查询数据库并将人口中的回显值(例如Population)放入文本框中(没有重新加载页面)回到网页上?我是否需要使displayCity.php类似于getData.php?我已经为文本框创建了一个新的Ajax方法,但我不确定是否需要这个。建议将不胜感激。
<?php include_once "connection.php"; ?>
<!DOCTYPE html>
<html>
<head>
<title>City displayer</title>
<h1>City displayer</h1>
<link rel="stylesheet" type="text/css" href="homepagestyle.css">
</head>
<body>
<div class = "country">
<label>Select Country: </label>
<select name="country" onchange="getId(this.value);">
<option value = "">Select Country</option>
<?php
$query = "SELECT DISTINCT(Country) from location AS Country FROM location ORDER BY Country ASC;";
$results = mysqli_query($con, $query);
foreach ($results as $country) {
?>
<option value = "<?php echo $country['Country']; ?>"><?php echo $country['Country'] ?></option>
<?php
}
?>
</select>
</div>
</br>
</br>
<div class="city">
<label>Select a City: </label>
<select name="city" id="cityList" onchange="showCity(this.value)">
<option value="">Select a city</option>
</select>
</div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
function getId(value){
$.ajax({
type: "POST",
url: "getdata.php",
data: "Country="+value,
success: function(data){
$("#cityList").html(data);
}
});
}
</script>
</br>
<div id = "textbox">Choose a country and city to display city name here</div>
<script>
function showCity(value){
$.ajax({
type: "POST",
url: "displayCity.php",
data: "City="+value,
success: function(data){
$("#textbox").html(data);
}
});
}
</script>
</body>
</html>
访问getdata.php
<?php
include_once "connection.php";
if(!empty($_POST['Country'])){
$country = $_POST['Country'];
$query = "SELECT * FROM location WHERE Country= '$country'";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['Country']; ?>"><?php echo
$city['City'] ?></option>
<?php
}
}
?>
答案 0 :(得分:1)
使用AJAX和$ _SESSION变量。无需将其写入数据库。您只需确保在任何需要的地方使用session_start()。