0

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

<?php echo form_dropdown('subject1', $dropdown_subjects,'',
 'class="required" id="subject1"'); ?>

现在,当任何人从上面的下拉列表中选择任何值时,我想使用 jquery 将值发送到我的控制器并在下表中查询( 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?

我的观点:

   <script>
           $(function(){

                 $("#subject").change(function(){
            $.ajax({
            url: "<?echo base_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   

     </script>




  <?php echo form_dropdown('subject1', $dropdown_subjects,'',
   'class="required" id="subject1"'); ?>



   <select name="teacher" id="teacher">
    <option value="">Select</option>
  </select>

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

提前致谢 :)

4

2 回答 2

3

您可以通过使用 jquery ajax 来做到这一点。首先,您将subject_id发布到 ajax 页面,ajax 页面将在组合框中返回教师列表,然后将结果填充到第一页中。

$("#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 .= "<option value='".$row->teacherid."'>".$row->teachername."</option>";
    }

    echo $output; // HTML example
于 2012-04-30T06:23:47.573 回答
0

你可以这样做:

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

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

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

于 2012-04-29T21:30:36.683 回答