如何以html格式显示数组是codeigniter中的自动完成搜索字段

时间:2016-11-18 12:12:50

标签: php html json ajax codeigniter

我使用codeigniter创建了一个自动完成搜索字段,结果将出现在像

这样的数组中
({"destination":"Accra"},{"destination":"Lagos"}) 

我希望将其转换为html并在输入字段的下拉列表中显示。我尝试了很多不同的方法,但可以成功,请帮助我。

以下是我的视图,模型和控制器的代码:

查看:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome to CodeIgniter</title>


</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<script>
$(document).ready(function(){
    $('#country_id').keyup( function() {
        var min_length = 0; 
    var keyword = $('#country_id').val();
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'http://localhost/new/index.php/travels/search_fields',
            type: 'POST',
            data: { term: $("#country_id").val()},
            success:function(data){
                $('#country_list_id').show();
                $('#country_list_id').html(data);
            }
        });
    } else {
        $('#country_list_id').hide();
    }
});
}); 
</script>

<form action="" method="post">
<input type="text" name="country_id" id="country_id" onKeyUp="do_search();" >

  <ul id="country_list_id">   </ul>                 
</form>

</body>
</html>

型号:

public function search_field($country_id){
    $this->db->select("destination");
    $this->db->from('travels_detail');
    $this->db->like('destination', $country_id);
    $query = $this->db->get();
    return json_encode($query->result_array());
}

控制器:

public function search_fields(){
         $this->load->helper('form');
    $country_id = $this->input->post('term');
    $data['var']= $this->travel->search_field($country_id);
    echo $data['var'];
}

1 个答案:

答案 0 :(得分:0)

如果您的数据来自服务器(作为json),请尝试使用以创建列表:

success: function(data) {
    var $countryList = $('#country_list_id');

    // Clear the list
    $countryList.empty();

    // Append all items as <li> elements
    data.forEach(x => {
        $countryList.append("<li>" + x.destination + "</li>");
    });

    // Show the list
    $countryList.show();
}