更新:通过禁用干扰 Ajax 成功响应的 CodeIgniter Profiler 来实现这一点。我认为它在 JSON 响应中添加了一个 div。
我正在尝试使用 mysql 数据库中的数据填充依赖选择框。问题是,尽管响应 Ajax 请求以正确的格式获取数据,但相关选择框并未得到填充。
请帮助我,因为我对这里发生的事情一无所知。下面是我的 JavaScript 代码。
<script type="text/javascript">
$(document).ready(function(){
    $('#country').change(function(){ 
        $("#cities > option").remove(); 
        var form_data = {
            country: $('#country').val(),
            csrf_token_name: $.cookie("csrf_cookie_name")
        };
        $.ajax({
            type: "POST",
            url: "http://localhost/outlets/get_cities", 
            data: form_data,
            dataType : "JSON",
            success: function(cities)
            {
               $.each(cities,function(id,name)
                {
                    var opt = $('<option />'); 
                    opt.val(id);
                    opt.text(name);
                    $('#cities').append(opt); 
                });
            }
        });
    });
});
</script>
这是HTML。我正在使用 Codeigniter。
<form id="form">
<?php $cities['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</form>
这是控制器:
function get_cities(){
    $country = $this->input->post('country');
  $this->load->model('city');
  header('Content-Type: application/x-json; charset=utf-8');
  echo (json_encode($this->city->get_cities($country)));
}
& 该模型:
function get_cities($country = NULL){
  $this->db->select('id, name');
  if($country != NULL){
      $this->db->where('countries_id', $country);
  }
  $query = $this->db->get('cities');
  $cities = array();
  if($query->result()){
      foreach ($query->result() as $city) {
          $cities[$city->id] = $city->name;
      }
  return $cities;
  }else{
      return FALSE;
  }
}