如何使用带有codeigniter的数据库中的JQuery使用自动完成功能?

Posted

技术标签:

【中文标题】如何使用带有codeigniter的数据库中的JQuery使用自动完成功能?【英文标题】:How to use autocomplete using JQuery from database with codeigniter? 【发布时间】:2016-10-16 04:02:44 【问题描述】:

这是我的搜索类型,代码如下:

<input type="text" required ="required"name="city_code" id="code" autocomplete="off" class="form-control">

这是我尝试做的 jquery:

function city_value()

    return '/ajax/get_address_list?city_code='+$('#code').val();


$tmp_location=;

$('#code').autocomplete(
    serviceUrl:city_value,
    minChars:2,
    lookupLimit: 25,
    focus_suggestion:true,
    transformResult: function(response) 
        $tmp_location=$.parseJSON(response);
        return 
            suggestions: $tmp_location
        ;
    
);

这是我的搜索自动完成类型控制器:

function get_address_list()
    $post_code= $this->input->get("city_code",true);
    $location_list=$this->ajax_m->m_get_address_like($post_code);
    echo json_encode($location_list);

这是模型:

function m_get_address_like($city_code)
    $sql = "SELECT `singapore_address`,`singapore_postal_code`
            FROM `uhd_singapore_address`
            WHERE `singapore_postal_code`='$city_code%' OR (singapore_address LIKE '$city_code%')";
    $query=$this->db->query($sql);
    return $query->result_array();

我已经使用 firebug 进行了检查,并且在我的 autocomplete.js 中出现以下错误

Autocomplete.formatResult = function (suggestion, currentValue) 
    var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';

    return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');// in this line
;

【问题讨论】:

能否添加控制台错误截图? jQuery UI 中有一个插件可以帮到你很多 【参考方案1】:

jQuery UI 中有一个自动完成插件:https://jqueryui.com/autocomplete/

使用这个,逻辑是这样的:

型号

function m_get_address_like($city_code)
    $sql = "SELECT `singapore_address`,`singapore_postal_code`
            FROM `uhd_singapore_address`
            WHERE `singapore_postal_code`='$city_code%' OR (singapore_address LIKE '$city_code%')";
    $query=$this->db->query($sql);
    //return $query->result_array();
    //I would replace the upper line by the next code:
    $sug_singapore_address = array();
    $sug_singapore_postal_code = array();
    foreach ($query->result() as $value) 
        $sug_singapore_address = $this->metadata($value->singapore_address);
        $sug_singapore_postal_code = $this->metadata($value->singapore_postal_code);
    
    $metadata->sug_singapore_address_implode = implode(", ", $sug_singapore_address);
    $metadata->sug_singapore_postal_code_implode = implode(", ", $sug_singapore_postal_code);
    return $metadata

控制器:

function get_address_list()
    $post_code= $this->input->get("city_code",true);
    $location_list=$this->ajax_m->m_get_address_like($post_code);
    $sug_singapore_address = array();
    $sug_singapore_postal_code_implode = array();
    foreach($location_list as $value)
    
        $sug_singapore_address[] = $value->sug_singapore_address_implode;
        $sug_singapore_postal_code[] = $value->sug_singapore_postal_code_implode;
    
    $singapore_address = array_unique($sug_singapore_address);
    $singapore_postal_code = array_unique($sug_singapore_postal_code);

查看:

<script>
    $(function() 
        var singapore_address = ['<?php echo implode("','",$singapore_address); ?>'];
        var sug_singapore_postal_code = ['<?php echo implode("','",$sug_singapore_postal_code); ?>'];
    ...
    

    $( "#city_code" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) 
            if ( event.keyCode === $.ui.keyCode.TAB &&
                $( this ).data( "ui-autocomplete" ).menu.active ) 
            event.preventDefault();
            
        )
    .autocomplete(
        minLength: 0,
        source: function( request, response ) 
            // delegate back to autocomplete, but extract the last term
            response( $.ui.autocomplete.filter(
                sug_singapore_postal_code, extractLast( request.term )
            ) );
        ,
        focus: function() 
            // prevent value inserted on focus
            return false;
        ,
        select: function( event, ui ) 
            var terms = split( this.value );
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push( ui.item.value );
            // add placeholder to get the comma-and-space at the end
            terms.push( "" );
            this.value = terms.join( ", " );
            return false;
        
    );

【讨论】:

【参考方案2】:

示例响应数据如下所示:

[
   
      "label":"Some Label",
      "value":"Some Value" //If not given it will take value from `label`
   ,
   
      "label":"Some Label",
      "value":"Some Value"
   ,
   
      "label":"Some Label",
      "value":"Some Value"
   ,
   
      "label":"Some Label",
      "value":"Some Value"
   
]

JS 代码:

function city_value()

    return '/ajax/get_address_list?city_code='+$('#code').val();


$("#currency_prefix").autocomplete(
        source: city_value,
        minLength: 2,
        autoFocus: false,
        delay: 500,
        select: function (event, ui) 
           // ui.item result item you can do any operation after result selected.
        ,
        response: function (event, ui) 
            if (ui.content.length == 1 && ui.content[0].id != 0) 
                ui.item = ui.content[0];

                $(this).val(ui.item.address);
            
        ,
    );

控制器:

function get_address_list()
    $post_code= $this->input->get("city_code",true);
    $location_list = $this->ajax_m->m_get_address_like($post_code);
    $data = array();
    foreach($location_list as $list_location) 
        $data[] = array(
            'label' => $list_location->singapore_postal_code, //This will be displayed when user types on autocomplete input field. It should be `label`.
            'value' => $list_location->singapore_address, //This will be displayed once user selected any of the listed results on the input. It should be `value`.
            'address' => $list_location->singapore_address, //Extra columns for later operations if any.
            ...//Other Column defnitions
         );     
    
    echo json_encode($data);

型号:

function m_get_address_like($city_code)
    $this->db->select('singapore_address, singapore_postal_code');
    $this->db->like('singapore_postal_code', $city_code,'after');
    $this->db->or_like('singapore_address', $city_code,'after');

    $q = $this->db->get('uhd_singapore_address');
    if($q->num_rows() > 0) 
       foreach($q->result() as $row) 
           $data[] = $row;
       
       return $data;
    
    return false;

我还没有测试过。自己试试吧。如果出现任何错误,请添加评论,否则享受编码。

【讨论】:

【参考方案3】:

视图:

这是视图文件中的一行:

<?php echo json_encode($my_data); ?>

控制器:

 function jsonData() 



        if ($this->input->get('type') == 'country_table') 

            $query = $this->db->get('leverantor');
            $this->db->select('leverantors_namn, leverantors_nr, lastbararavtal');
            $this->db->from('leverantor');

            $this->db->where('leverantors_nr =' . $this->input->get('name_startsWith'));
            $this->db->limit(1);
            $query = $this->db->get();


            foreach ($query->result() as $row) 
                $arr[''] = $row->leverantors_nr."|".$row->leverantors_namn."|".$row->lastbararavtal;

            
        

        $data["my_data"] = $arr; //$this->entries->autocomplete($this->input->get('name_startsWith'));   //$this->example_model->get_examples($this->input->post('name1'),$this->input->post('name2'));
        $this->load->view('json/json_example_view', $data);
    

查看:

<?php
                    $leverantors_nr = array(
                        'name' => 'leverantors_nr',
                        'type' => 'text',
                        'id' => 'leverantors_nr',
                        'value' => $this->input->post('leverantors_nr'),
                        'placeholder' => 'Leverantörs Nr.',
                        'class' => 'span4'
                    );
                    ?>
                    <?= form_input($leverantors_nr); ?>



    <script type="text/javascript">

    $('#leverantors_nr').autocomplete(
    source: function(request, response) 
    $.ajax(
    url : 'palla/jsonData',
            dataType: "json",
            data: 
            name_startsWith: request.term,
                    type: 'lev_table',
                    row_num : 1
            ,
            success: function(data) 
            response($.map(data, function(item) 
            var code = item.split("|");
                    return 
                    label: code[0],
                            value: code[0],
                            data : item
                    
            ));
            
    );
    ,
            autoFocus: true,
            minLength: 1,
            select: function(event, ui) 
            var names = ui.item.data.split("|");
                    $('#leverantors_namn').val(names[1]);

            

         

        );

    </script>

【讨论】:

以上是关于如何使用带有codeigniter的数据库中的JQuery使用自动完成功能?的主要内容,如果未能解决你的问题,请参考以下文章

Codeigniter:如何使用 jQuery 添加带有多选和删除复选框的列

codeigniter 中的友好 url,带有 url 中的变量

带有 Codeigniter 的 Croppic jQuery 插件

Codeigniter,如何将第三方文件夹中的 jwt 库与模型结合使用?

如何从 CodeIgniter 中的视图访问模型

如何将带有数据的http标头发送到rest Api codeigniter?