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

时间:2016-06-15 07:21:59

标签: jquery codeigniter autocomplete

这是我的搜索类型,包含以下代码:

<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
};

3 个答案:

答案 0 :(得分:0)

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;
        }
    });

答案 1 :(得分:0)

样本响应数据如下:

[
   {
      "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;
}

我尚未测试。自己尝试一下。如果发生任何错误,请添加评论,否则享受编码。

答案 2 :(得分:-1)

视图:

这是视图文件中的单行:

<?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>