我正在尝试创建一个表单,当用户首先选择一个国家/地区时,然后应该显示所选县的所有城市的列表。请参阅以下代码:
<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;
}
}
?>
首先,您需要更改服务器端代码以返回 json。循环访问您获得的城市,并将它们添加到数组中,索引作为城市的 id,值作为城市的名称。然后,回显 json_encode($cityArray) 而不是返回$cities。
然后,在jQuery中,你需要像下面这样构造元素:
$.post('Showcountries.php', { valueSelected: valueSelected}, function(results){
var resultsObj = jQuery.parseJSON(results);
var optionsHTML = '';
$(resultsObj).each(function() {
optionsHTML += '<option value="'+ this.cityId +'">'+ this.cityName +'</option>';
});
$('#citiesS').html(optionsHTML);
});