【问题标题】:How to append successful AJAX response to Drop down values in Codeigniter?如何将成功的 AJAX 响应附加到 Codeigniter 中的下拉值?
【发布时间】:2020-01-07 05:09:56
【问题描述】:

我需要先从下拉列表中选择部门,然后需要在另一个下拉列表中加载该特定部门的官员。我在 Codeigniter 中这样做。

查看 (第二个下拉列表,我必须加载官员姓名。我已经加载了部门下拉列表的值,并且在选择部门后,此下拉列表应该获取选择值)

<div class="form-group">
   <select name="Officer_InCharge" id="Officer_InCharge" class="form-control input-lg">
      <!--<option value="">Select officer</option>-->
   </select>
</div>

我的 AJAX

<script>
  $(document).change(function(){
    $("#Officer_Dept").click(function(){
      var Dept = $('#Officer_Dept').val();
      if (Dept != '') 
      {
        $.ajax({
          url:"<?php echo base_url();?>Crud/fetch_officers",
          method:"POST",
          data:{Dept:Dept},
          //dataType: 'json',
          success:function(data)
          {

            alert(data);

            var options = "";
             for (var i = 0; i < data.length; i++) {
                 options += "<option>" + data[i].user_name + "</option>";
             }
             $("#Officer_InCharge").html(options);
          }
        })
      }
  });
});
</script>

AJAX 调用成功,我面临的问题是将 ajax 响应附加到选择下拉的官员。这些值显示在警报中

alert(data);

但没有显示在下拉列表中。

我的控制器

public function fetch_officers()
    {
        if ($this->input->post('Dept')) 
        {
            echo $this->Crud_model->fetch_dept_officers($this->input->post('Dept'));

        }
    }

我的模型

function fetch_dept_officers($Dept)
    {
        $this->db->where('user_dept',$Dept);
        $this->db->order_by('user_name', 'ASC');
        $query = $this->db->get('tbl_users');

        $output = '<option value="">Select Officer</option>';
          foreach($query->result() as $row)
          {
            $output .= '<option value="'.$row->user_id.'">'.$row->user_name.'</option>';
            //$output += "<option value='"+$row->user_id+"'>"+$row->user_name+"</option>";
            //$output .= '<option>'.$row->user_name.'</option>';
            //formoption += "<option value='"+val+"'>"+val+"</option>";

            //
            //
          }
          return $output;
          //return $query->result();
    }

感谢是否有人可以解决这个问题。提前致谢。

【问题讨论】:

  • 您能告诉我,如果您从 ajax 调用返回选项,那么为什么要编写循环来创建选项?
  • 检查您的 ajax 响应数据。我认为您的数据形式为字符串类型。将字符串更改为对象。
  • 删除alert(data)并检查for循环是否被执行。
  • 我确实试过 $('Officer_InCharge').html(data);但是它仍然没有工作@Madhuri PAtel
  • 未定义的选项显示在下拉值中...

标签: php jquery ajax codeigniter


【解决方案1】:

试试这个

$('#Officer_Dept').change(function () {
    var Dept = $('#Officer_Dept').val();
    $.ajax({
        type: 'GET',
        url: base_url + '/Crud/fetch_officers',
        data: {
            Dept:Dept
        },
        success: function (data) {
            var html = '';
            $.each(data.data, function (i, value) {
                html += ('<option value="' + value.id + '">' + value.user_name + '</option>');

            });
            $("#Officer_InCharge").html(html);
        }
    });
});

//in controller

   function getInchargeOfficer(Request $request) {
        $inchargeOfficerArray = ModelName::where('dept', $request->Dept)->get();
        if (!empty($inchargeOfficerArray)) {
            return response()->json(['data' => $inchargeOfficerArray]);
        }
    }

【讨论】:

    【解决方案2】:

    在 ajax 中,您只需将 html 添加到选择框中。为此,您必须将以下代码放入 ajax 中。

    <script>
      $(document).change(function(){
        $("#Officer_Dept").click(function(){
          var Dept = $(this).val();
          if (Dept != '') 
          {
            $.ajax({
              url:"<?php echo base_url();?>Crud/fetch_officers",
              method:"POST",
              data:{Dept:Dept},
              //dataType: 'json',
              success:function(data)
              {
    
                $("#Officer_InCharge").html(data);
              }
            })
          }else{
             alert('Please select Department');
         }
      });
    });
    </script>
    

    在控制器中,您必须设置以下条件

    public function fetch_officers()
        {
            if ($this->input->post('Dept')) 
            {
                echo $this->Crud_model->fetch_dept_officers($this->input->post('Dept'));
    
            }else{
                echo "<option>No Officer Available.</option>";
            }
    
        }
    

    在模型中:

    function fetch_dept_officers($Dept)
        {
            $this->db->where('user_dept',$Dept);
            $this->db->order_by('user_name', 'ASC');
            $query = $this->db->get('tbl_users');
            $optionsResult=$query->result();
    
        if(count($optionsResult)>0){
        $output = '<option value="">Select Officer</option>';
    
          foreach($optionsResult as $row)
          {
            $output .= '<option value="'.$row->user_id.'">'.$row->user_name.'</option>';
            //$output += "<option value='"+$row->user_id+"'>"+$row->user_name+"</option>";
            //$output .= '<option>'.$row->user_name.'</option>';
            //formoption += "<option value='"+val+"'>"+val+"</option>";
    
            //
            //
          }
        }else{
         $output="<option>No Officer available</option>";
        }
          return $output;
          //return $query->result();
    }
    

    【讨论】:

      【解决方案3】:

      只需通过模型发送数组数据:

      function fetch_dept_officers($Dept)
          {
              $this->db->where('user_dept',$Dept);
              $this->db->order_by('user_name', 'ASC');
              $query = $this->db->get('tbl_users')->result_array();
      
              return $query ;
      
          }
      

      首先你需要将json编码数据从控制器发送到ajax。所以在控制器中做一些改变如下:

      public function fetch_officers()
      {
         if ($this->input->post('Dept')) 
         {
           $result_data=$this->Crud_model->fetch_dept_officers($this->input->post('Dept'));
           echo json_encode($result_data); //send encoded data
          }
       }
      

      在 ajax 中,您需要首先在 jquery 的帮助下解析该 json 并在 html 中设置数据。 请在下面找到ajax代码:

      $.ajax({
         url:"<?php echo base_url();?>Crud/fetch_officers",
         method:"POST",
         data:{Dept:Dept},
         success:function(data) {
            var parse_data = JSON.parse(data); //parse encoded data
            $.each(parse_data,function(index,value){
               $("#Officer_InCharge").append("<option>" + value.user_name + "</option>");   
            });
         }
      })
      

      【讨论】:

        【解决方案4】:

        只需要一个 div 或任何你想在其中附加数据的东西。在您的情况下,ID 是 Officer_InCharge,

        $("#Officer_InCharge").append(options);
        

        【讨论】:

          【解决方案5】:

          您只将查询的结果数组从您的模型传递到控制器,并且从控制器您可以返回 fetch_dept_officers 结果,并且在 AJAX 成功调用中您可以附加选项

          我的模特

            function fetch_dept_officers($Dept)
                  {
                      $this->db->where('user_dept',$Dept);
                      $this->db->order_by('user_name', 'ASC');
                      $query = $this->db->get('tbl_users');
          
                      return $query->result();
                  }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-07-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-08
            • 1970-01-01
            相关资源
            最近更新 更多