使用Codeigniter中的Jquery根据另一个下拉列表的选择填充下拉列表

我正在使用Codeigntier,我在我的视图文件中有以下下拉列表,其中填充了一系列主题。

 

现在,当任何人从上面的下拉列表中选择任何值时,我想使用下表中的jquery和query将值传递给我的控制器( SELECT teacherid from table3 WHERE subjectid=$subjectid)以获取teacherid以便我可以填充另一个下拉列表中的teacherid列表选择。 如果任何用户从第一个下拉列表中更改了他的选择,我想要更改第二个下拉列表的值

表名:table3

 subjectid teacherid 1 1001 2 1003 

所以底线是我想根据另一个下拉列表填充下拉列表。 我已经找到了关于这个主题的几个教程,但我无法理解那些(我知道我很愚蠢)。

如果我想实现这一目标,请您告诉我我的视图和控制器应该是什么样的?

谢谢 :)

编辑

嗨,这是我的控制器和视图文件的样子:

我的控制器

  $id= $this->input->post('subject_id'); //receiving the ajax post from view $this->db->select('teachername,teacherid'); $this->db->from('subject_teacher'); $this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid'); $this->db->where('subjectid',$id); $records = $this->db->get(''); $data=array(); $data[''] = 'Select'; foreach ($records->result() as $row) { $data[$row->teacherid] = $row->teachername; } return ($data); // I need help here... How to send the data as json? 

我的看法:

   $(function(){ $("#subject").change(function(){ $.ajax({ url: "mycontroller/function", data: {subject_id: $(this).val()}, type: "post", success: function(msg){ $("#teacher").html(); // I need help here...how do I get the value from controller and append to my another dropdown named teacher? }) }) }); // function ends here    Select  

请为我的视图和控制器进行必要的更改。

提前致谢 :)

您可以使用jquery ajax来完成此操作。 首先将subject_id发布到ajax页面,ajax页面将返回combobox中的teacher列表,然后在第一页中填充结果。

 $("#subject").change(function(){ $.ajax({ url: "your-ajax-page-url", data: {subject_id: $(this).val()}, type: "post", success: function(msg){ $("#teacher").html(); }) }) 

这是编辑过的控制器

  $id= $this->input->post('subject_id'); //receiving the ajax post from view $this->db->select('teachername,teacherid'); $this->db->from('subject_teacher'); $this->db->join('teacher', 'teacher.teacherid = subject_teacher.teacherid'); $this->db->where('subjectid',$id); $records = $this->db->get(''); $output = null; foreach ($records->result() as $row) { $output .= ""; } echo $output; // HTML example 

你可以这样做:

你将不得不在你的控制器中创建一个函数来填充数据,但不是输出你的视图,你必须把它放在像这样的var里面

 $outout = $this->load->view('myselect_output',$data,TRUE); 

然后在主视图中,您将不得不使用jquery或任何其他js库来操作DOM。