Ajax与codeigniter中的选择框

我有一个带有两个选择框的表单。 一个是城市,另一个是该地区。

我的要求。 当某人选择一个城市时,必须从数据库中捕获城市中的区域并显示在另一个选择框中。

我试过但是,我的阿贾克斯有问题。 这是我的代码如下。

视图

select <option value="city_id; ?>">name; ?>
Any <option value="ara_id; ?>">name; ?>

调节器

 function __construct() { parent::__construct(); //session, url, satabase is set in auto load in the config $this->load->model('Home_model', 'home'); $this->load->library('pagination'); } function index(){ $data['city'] = $this->home->get_city_list(); $data['type'] = $this->home->get_property_type_list(); $this->load->view('home', $data); } function get_area(){ $area_id = $this->uri->segment(3); $areas = $this->home->get_area_list($area_id); echo json_encode($areas); } 

模型

 function get_area_list($id){ $array = array('city_id' => $id, 'status' => 1); $this->db->select('area_id, city_id, name'); $this->db->where($array); $this->db->order_by("name", "asc"); $this->db->from('area'); $query = $this->db->get(); $result = $query->result(); return $result; } 

阿贾克斯

  $('#area_section').hide(); $('#city_select').on('change', function() { // alert( this.value ); // or $(this).val() if (this.value == 0) { $('#area_section').hide(600); }else{ //$("#area_select").html(data); $.ajax({ type:"POST", dataType: 'json', url:"", data: {area:data}, success: function(data) { $('select#area_select').html(''); $.each(data, function(item) { $("").val(item.area_id) .text(item.name) .appendTo($('select#area_select')); }); } }); $('#area_section').show(600); }; });  

一旦我选择了一个城市,它必须从数据库中获取城市中的所有区域,并将其显示在area_select选择框中。

谁能帮帮我吗。 谢谢。

尝试改变这种方式。

你的ajax代码

 //keep rest of the code $.ajax({ type:"POST", dataType: 'json', url:"", data: {area:$(this).val()},//send the selected area value 

同时在ajax成功函数中显示area_section

你的控制器function

 function get_area() { $area_id = $this->input->post('area'); $areas = $this->home->get_area_list($area_id); echo json_encode($areas); } 

希望它能解决你的问题

更新
尝试使用这样的ajax更新function

  success: function(data) { $('select#area_select').html(''); for(var i=0;i").val(data[i].area_id) .text(data[i].name) .appendTo($('select#area_select')); } }