2

我想使用 twitter bootstraps typeahead 插件创建一个自动建议字段。这是我当前的代码。它在检查元素控制台中返回 500 内部服务器错误。我认为问题出在模型上。请帮我。提前致谢。

查看:注册

<script type="text/javascript">
    $(function() {
        $('#office').typeahead({
            source: function(typeahead, query) {
                $.ajax({
                    url: "<?php echo base_url('main/get_offices'); ?>",
                    type: "post",
                    data: "search=" + query,
                    dataType: "json",
                    async: false,
                    success: function(data) {
                        typeahead.process(data);
                    }
                });
            }
        });
    });

控制器:主

public function get_offices() {
    $this->load->model('offices');

    $data = $this->offices->get();

    echo json_encode($data);

}

型号:办公室

public function get() {
    $office = $this->input->post('search');

    $this->db->select('name');
    $this->db->from('departments');
    $this->db->like('name', $office);
    $query = $this->db->get();

    $office_array = array();
    foreach ($query->result() as $row) {
        $office_array = $row->name;
    }
    //$data['office'] = $office_array;

    return $office_array;
}
4

1 回答 1

1

我在函数参数中使用 typeahead 尝试了您的代码,但似乎不受支持。我重写了您的代码以删除预先输入并在 ajax 调用范围之外返回结果。

$('#office').typeahead({
  source: function(query) {
    var result = [];
    $.ajax({
      url: "<?php echo base_url('main/get_offices'); ?>",
      type: "post",
      data: "search=" + query,
      dataType: "json",
      async: false,
      success: function(data) {
        alert(data); // verify that you actually get data from the model
        result = data;
      }
    });
    return result;
  }
});

模型函数 get 似乎有错字,在这部分

$office_array = array();
foreach ($query->result() as $row) {
    $office_array = $row->name;
}

应该是$office_array[]

$office_array = array();
foreach ($query->result() as $row) {
    $office_array[] = $row->name;
}
于 2012-10-04T03:02:58.320 回答