Codeigniter动态依赖下拉列表Ajax

时间:2018-12-12 06:11:53

标签: php jquery ajax combobox codeigniter-3

我有一个组合框/下拉链,适合在编辑数据时使用,如果更改了下拉菜单中的数据,则在PIC下拉列表中填充的数据不会更改, PIC被更改了,但是这不是,如果创建的数据是正常的,那是正常的,因为在下拉列表中它尚未填写,我该如何解决?

此处的控制器

public function viewCreated()
{
    $departm = $this->db->get('office')->result();
    $where = array('username' => $this->session->userdata('name'));
    $data = array(
        'id_monitoring' => $this->m_data->uniqueID(),
        'dept' => $this->m_data->data_dept()->result(),
        'pic' => $this->m_data->getNamefromDept()->result(),
        'name' => $this->m_data->cek_name($where)->result(),
        'departm' => $departm,
    );
    $this->load->view('manage/v_create', $data);
}    

public function dataPicE($id)
{
    $result = $this->db->where('department', $id)->get('admin')->result();
    echo json_encode($result);
}

在这里查看

<div class="form-group">
    <label>Department</label>
    <select class="form-control select2" style="width: 100%;" name="department" placeholder="Select Group" id="Depart" required>
    <option value=""></option>
    <?php foreach ($departm as $u => $value) { ?>
         <option value="<?php echo $value->id; ?>"><?php echo $value->department; ?></option>
    <?php } ?>
    </select>
</div>

<div class="form-group">
    <label>PIC</label>
    <select class="form-control select2" style="width: 100%;" name="pic" placeholder="Select Group" id="PIC" required>
    </select>
</div>

此处路由

$route['manage/v_edit'] = 'Admin';
$route['manage/v_edit/ajax/(:any)'] = 'dataPicE';

JS在这里

<script type="text/javascript">
    $(document).ready(function(){
        $('select[name="department"]').on('change', function(){
            var departID = $(this).val();
            if(departID){
                $.ajax({
                    url: 'dataPicE/'+departID,
                    type: 'GET',
                    dataType: 'json',
                    success:function(data){
                        //$('select[name="pic"]').empty();
                        $('select[name="pic"]').show();
                        $.each(data, function(key, value){
                            $('select[name="pic"]').append('<option value="'+value.name+'">'+value.name+'</option>')
                        });
                    }
                });
            } else {
                $('select[name="pic"]').empty();
            }
        });
    });
</script>

我希望有人可以帮助我学习

0 个答案:

没有答案