2012-04-29 60 views
0

使用jQuery我使用Codeigntier和我在我的視圖文件下面的下拉其填充的科目列表中的另一個下拉列表中選擇一個下拉。填充基於在笨

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

現在,當任何一個選擇上方的下拉列表任何價值,我想使用下表(SELECT teacherid from table3 WHERE subjectid=$subjectid)在jQuery和查詢來獲取teacherid值發送到我的控制器,這樣我可以填充在teacherid列表另一個下拉選擇。如果任何用戶從第一個下拉改變他的選擇我想第二個下拉值也

改變

表名:表3

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> 

請在我的視圖和控制器中進行必要的更改。

感謝提前:)

回答

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 
+0

@ UTTAM感謝您的答覆。請檢查我上面的帖子的編輯部分。謝謝:) –

+0

使用[json_encode()](http://php.net/manual/en/function.json-encode.php)函數以json格式發送數據並在javascript中解碼或者您只需在html中返回數據格式。 – uttam

+0

你能告訴我怎麼做嗎? –

0

你可以做這樣的:

你必須創建你的控制器內的功能,這將填充數據,但不輸出你的看法,你將不得不把像這樣

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

,然後在你的主視圖,你將不得不處理與jQuery的DOM或任何其他JS庫一個變種內..