从属下拉菜单,第二个下拉菜单未填充,Codeigniter

Dependent dropdown, second dropdown not populated, Codeigniter

我有一个从属下拉列表,它在第一个下拉列表中获取类别,应该在第二个下拉列表中获取子类别,但子类别下拉列表未填充。我的模型中有这样的东西:

public function category()
{
    $response = array();

    $this->search(array(), 'date_created');

    $this->db->select('*');
    $query = $this->db->get('categories');
    $response = $query->result_array();

    return $response;
}
public function sub_category($parent_id)
{
    $query = $this->db->get_where('sub_categories', array('parent_id' => $parent_id));

    return $query->result_array();
}

然后在我的控制器上出现类似这样的东西:

public function edit_product($id)
{
    $data['title'] = 'Update Product';

    $this->load->view('../admin/template/admin_header');
    $products = new Admin_model;
    $data['products'] = $products->edit_product($id);
    $data['category'] = $this->Admin_model->category();
    $data['subcategory'] = $this->Admin_model->sub_category($data['products']->category_id);
    $this->load->view('../admin/template/admin_topnav');
    $this->load->view('../admin/template/admin_sidebar');
    $this->load->view('../admin/products/manage_product', $data);
    $this->load->view('../admin/template/admin_footer');
}

function get_subcategory()
{
    if ($this->input->post('parent_id')) {
        echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
    }
}
public function insert_product()
{
    $productData = array();

    if ($this->input->post('productData')) {
        $this->form_validation->set_rules('category_id', 'Category', 'required');
        $this->form_validation->set_rules('sub_category_id', 'Sub Category', 'required');
        $this->form_validation->set_rules('product_name', 'Product Name', 'required');
        $this->form_validation->set_rules('department', 'Department', 'required');
        $this->form_validation->set_rules('description', 'Description', 'trim|required');
        $this->form_validation->set_rules('status', 'Status', 'required');

        if ($this->form_validation->run() == true) {
            $ori_filename = $_FILES['product_image']['name'];
            $update_image = time() . "" . str_replace(' ', '-', $ori_filename);
            $config = [
                'upload_path' => './images/products',
                'allowed_types' => 'gif|jpg|png',
                'file_name' => $update_image,
            ];

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('product_image')) {
                $error = array('error' => $this->upload->display_errors());
                $this->load->view(base_url('admin/products'), $error);
            } else {

                $image = $this->upload->data('file_name');
                $productData = array(
                    'category_id' => $this->input->post('category_id'),
                    'sub_category_id' => $this->input->post('sub_category_id'),
                    'product_name' => $this->input->post('product_name'),
                    'department' => $this->input->post('department'),
                    'description' => $this->input->post(htmlentities('description')),
                    'status' => $this->input->post('status'),
                    'upload_path' => $image
                );
                $img = new Admin_model;
                $img->insert_product($productData);
                $this->session->set_flashdata('status', 'Package InsertedSuccesfully');
                redirect(base_url('admin/products'));
            }
        }
    }

    $data['title'] = 'Insert Product';
    $data['category'] = $this->Admin_model->category();
    $data['subcategory'] = $this->Admin_model->get_subcategory();

    $this->load->view('../admin/template/admin_header');
    $this->load->view('../admin/template/admin_topnav');
    $this->load->view('../admin/template/admin_sidebar');
    $this->load->view('../admin/products/manage_product', $data);
    $this->load->view('../admin/template/admin_footer');
}

然后是视图:

    <div class="form-group">
  <label for="" class="control-label"> Category</label>
  <select name="category_id" id="category" class="custom-select select">
    <option value="">Select Category</option>
    <?php
       foreach ($category as $row) {
             echo '<option value="' . $row['id'] . '"';
             if (isset($products) && $row['id'] == $products->category_id) {
                  echo ' selected';
             }
                echo '>' . $row['category'] . '</option>';
             }
   ?>
    </select>
</div>
<div class="form-group">
  <label for="" class="control-label">Sub Category</label>
  <select name="sub_category_id" id="subcategory" class="custom-select select">
    <option value="">Select Sub Category</option>
    <?php
      foreach ($subcategory as $row) {
          echo '<option value="' . $row['id'] . '"';
          if ($row['id'] == $products->sub_category_id) {
              echo ' selected';
          }
              echo '>' . $row['sub_category'] . '</option>';
         }
    ?>
  </select>
</div>

这是脚本。我对 AJAX 不是很熟悉,所以我试着在这里提问并获得答案,这有助于我进步,但我仍然无法填充子类别下拉列表。

<script type="text/javascript">
$(document).ready(function() {

    $('#category').change(function() {
        var parent_id = $('#category').val();
        console.log(parent_id)
        if (parent_id != '') {
            $.ajax({
                url: "<?php echo base_url(); ?>admin/get_subcategory",
                method: "POST",
                data: {
                    parent_id: parent_id
                },
                success: function(data) {
                    $('#subcategory').html(data);
                    console.log(data)
                }
            });
        } else {
            $('#subcategory').html('<option value="">Select Category First</option>');
        }
    });
});

另外,这是我在控制台中得到的

$this->Admin_model->sub_category(...) 的结果是一个数组。 echo 仅适用于字符串值,这就是您收到错误的原因。您需要遍历结果数组(在 admin/get_subcategory 中)并一个一个地打印值。还用 <option> 标记将每个值括起来,这样就可以将结果放在 select 框中而无需进一步修改:

  public function get_subcategory() {
    if ($this->input->post('parent_id')) { 
      $subcategories = $this->Admin_model->sub_category($this->input->post('parent_id'));
      foreach ($subcategories as $subcategory) {
        echo '<option value="'.$subcategory['id'].'">'.$subcategory['sub_category'].'</option>';
      }
    }
  }