-1

我正在尝试创建一个表单,当用户首先选择一个国家/地区时,然后会出现所选县的所有城市的列表。请参阅以下代码:

<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;

}


}
?>
4

1 回答 1

-1

首先,您需要更改服务器端代码以返回 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);
  }); 
于 2013-09-29T17:32:32.180 回答