我正在尝试创建一个表单,当用户首先选择一个国家/地区时,然后会出现所选县的所有城市的列表。请参阅以下代码:
<select name="country" id="countryS">
<option value="">Select Country</option>
<option value="1">USA</option>
<option value="2">RUSSIA</option>
<option value="3">United Kingdom</option>
</select>
<select name="city" id="citiesS">
<option value="">Select City</option>
</select>
然后使用 JQuery 我使用以下代码:
$('#countryS').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
$.post('Showcountries.php', { valueSelected: valueSelected}, function(results){
});
我的问题是如何使用上面的 jQuery 代码,以便能够在下面的 html 代码中显示适当的城市?
<select name="city" id="citiesS">
<option value="">Select City</option>
</select>
在showCountries.php
我存储了以下代码:
<?php
require_once('../class.myclass.php');
if(isset($_POST['valueSelected'])){
$selectedVal = $_POST['valueSelected'];
if(!empty($selectedVal)){
$locations = new location();
$cities = $locations->TheCities($selectedVal);
return $cities;
}
}
?>
最后在class.myclass.php
我有下面的代码,它返回所有适当的城市。
<?php
class location
{
private $host = "xxxxxxxx";
private $user = "xxxxxxxx";
private $password = "xxxxxxxx";
private $name = "xxxxxx";
public function TheCities($country)
{
$db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->name, $this->user, $this->password);
$sql = "SELECT * FROM CITIES WHERE COUNTRY = :country";
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':country' => $country));
$results = $sth->fetchAll();
return $results;
}
}
?>