在codeigniter中链式ajax请求

时间:2013-01-02 04:24:24

标签: ajax codeigniter jquery

我有一个使用自动完成的表单,我可以检索输入字段上的数据,但我无法弄清楚如何获取描述数据。我想要做的是从用户获取值然后调用另一个控制器以使用ajax获取附加信息(这样我可以在需要时获得更多信息)。谢谢

查看

<script type="text/javascript">
$(document).ready(function() {
$(function() {
    $( "#autocomplete" ).autocomplete({
        source: function(request, response) {
            $.ajax({ url: "<?php echo site_url('test/suggestions'); ?>",
            data: { term: $("#autocomplete").val()},
            dataType: "json",
            type: "POST",
            success: function(data){
                response(data);
            }
        });
    },
    minLength: 2

    });
});
});
</script>

<label for="title">Job Title</label>
<input name="title" type="text" id="autocomplete" />

<label for="description">Description</label>
<p id="description" /></p>

控制器

 function suggestions()
{
    $this->load->model('tp_model');
    $term = $this->input->post('term',TRUE);

    if (strlen($term) < 1) break;

    $rows = $this->tp_model->GetAutocomplete(array('keyword' => $term));

    $title_array = array();
    $description_array = array();


    foreach ($rows as $row){
         array_push($title_array, $row->title); 
         array_push($description_array, $row->description);

}
    echo json_encode($title_array);     

}

模型

  function GetAutocomplete($options = array())
{

    $this->db->select('*');
    $this->db->from('test');
    $this->db->like('title', $options['keyword'], 'after');
    $query = $this->db->get();
    return $query->result();

}

1 个答案:

答案 0 :(得分:0)

您可以使用“select”事件从控制器中获取说明以进行自动填充。

$("input#autocomplete").autocomplete({
    source: ...,
    .....,
    select: function(event, ui) {
        var id = ui.item.id;
        $.ajax({
            url: description_fetch_url, //another controller
            data: "descritpion_id="+id,
            ....
            success: function(data) {
                $("#description").html(data)
            } 
        });
    }
});