如何在视图页面中填充下拉列表?

时间:2014-09-27 06:53:05

标签: codeigniter

查看文件:

"<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <script type="text/javascript">
 function getval(get)
    {
     var id =  get.value;
    //alert(id);
    $.ajax({
    type : "POST",
    url :"/admin/ajax",
    data :{id:id},
    success:function(data){
    alert(data);
    //$('#sub_category').html(data);//window.location = "<?php echo site_url('admin/examdetails/form'); ?>"
    }
    });  
    }
  </script>

Controller:
         function ajax(){
          $id = $_POST['id'];
          // print_r($id);
          $this->load->model('admin_model');
          $query =$this->admin_model->get_sub_details($id);
           echo  '<select name="sub_category" id="sub_category">';
           //print_r($query->result_array());
           //exit();
           foreach($query->result_array() as $row){
           $name = $row['s_name']; 
           $id  = $row['s_id'];
           echo'<option name="category" id="category"  value="'.$id.'">';
           echo $name;
           echo'</option>';
           echo'</select>';
        } 
        }

如何在视图中打印Dropdown

1 个答案:

答案 0 :(得分:0)

只需使用您的ajax请求从控制器获取JSON数据,过滤该json数据并收集javascript变量并将其传递到同一视图中定义的子类别中。

希望这是有道理的:

IN控制器:

// Send only JSON data on request 
function ajax(){
      $id = $_POST['id'];
      // print_r($id);
      $this->load->model('admin_model');
      $query =$this->admin_model->get_sub_details($id);
      $result = $query->result_array();

      // Send Data only in JSON Format
      $this->output
               ->set_content_type("application/json")
               ->set_output(json_encode(array('data'=>$result)));
    } 

在视图中:

<select name="sub_category" id="sub_category"></select>

IN JS:

//send ajax request to get the JSON data for Categories
$.ajax({
    type : "POST",
    url :"/admin/ajax", 
    dataType: 'json', 
    data :{id:id},
    success:function(response){
       var _option = '';
       // Filter JSON data and Collect in Option
       $.each(resonse.data, function(i, data) {
           _option += '<option value="'+data.s_id+'">'+data.s_name+'</option>';
       });

       // Add Options to Sub Category
       $('#sub_category').html(_option);
    }
});  

同时阅读代码中的应用注释以了解它。