将ajax数组数据加载到select2下拉格式

时间:2016-08-24 05:34:16

标签: javascript php ajax codeigniter jquery-select2

我在从ajax脚本填充下拉数据时遇到问题。 这是我的控制器:

public function ajax_get_kota($idProv='')
{
    $kota = $this->data['namaKota'] = $this->registrasi_model->get_nama_kota($idProv);
    echo json_encode($kota);
}

这是我的模特:

public function get_nama_kota($idProv='')
{
    $query = $this->db->query('SELECT id_kab, nama FROM kabupaten WHERE id_prov = '.$idProv.' ORDER BY nama ASC');
    return $dropdowns = $query->result();
}

并查看:

<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">        
    <?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
    <div class="col-sm-3">
       <?php
            $atribut_kota = 'class="form-control dropKota"';
            echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
            set_validation_icon('Kota');
        ?>
    </div>
    <?php if (form_error('Kota')) : ?>
        <div class="col-sm-9 col-sm-offset-3">
            <?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
        </div>
    <?php endif ?>

    <script>
        $(document).ready(function () {
            $(".dropProv").on("change", function(){
                var idProv = $(this).val();
                var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
                var kota = [];
                $.ajax({
                    url: baseUrl,
                    data: kota,
                    success: function(datas){
                        $(".dropKota").select2({
                             placeholder: "Pilih Kota",
                             data: datas
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error");
                    }
                });
            });
        });
    </script>
</div>

我在这里尝试做的是如何传递我从ajax获取的数据:

  

[{“id_kab”:“5103”,“nama”:“KAB.BADUNG”},{“id_kab”:“5106”,“nama”:“KAB.BANGLI”},{“id_kab”:“ 5108“,”“nama”:“KAB.BULELENG”},{“id_kab”:“5104”,“nama”:“KAB.GIANYAR”},{“id_kab”:“5101”,“nama”:“KAB。 JEMBRANA“},{”id_kab“:”5107“,”nama“:”KAB.KARANGASEM“},{”id_kab“:”5105“,”nama“:”KAB.KLUNGKUNG“},{”id_kab“:” 5102“,”“nama”:“KAB.TABANAN”},{“id_kab”:“5171”,“nama”:“KOTA DENPASAR”}]

进入Dropdown dropKota。当另一个下拉值发生变化时,动态生成这些数据。

目前的结果:

enter image description here

select2需要特定格式,以便在下拉列表中正确显示

  

var data = [{id:0,text:'enhancement'} //类似这样的

我该怎么做?

4 个答案:

答案 0 :(得分:1)

试试这个:

success: function(datas){
    var data = JSON.parse(datas);

    var options = '<select name="dd_name"><option>Select</option>';
    for(i=0; i<data.length; i++)
    {
        options += '<option value="'+ data.col_name +'">'+ data.col_id +'</option>';
    }
    options += '</select>';

    $('#div_id').html(options);   // where #div_id is the id of a div in which this drop down is required.
},

答案 1 :(得分:1)

你必须这样做:

 $.ajax({
                url: url,
                type: "POST",
                async: false,
                data: {id: id},
                success: function(data) {
                    var data_array = $.parseJSON(data);
                    $.each(data_array.emp, function(key, value) {
                        $('#Your_drop_down_id').append($('<option>', {
                            value: key,
                            text: value,
                        }));
                    });

                }
            });

你必须解析数据(JSON到数组),然后使用$ .each来循环所有值。

答案 2 :(得分:0)

如下所示更改$.ajax电话

$.ajax({
    url: baseUrl,
    data: kota,
    dataType: "JSON",
    success: function(datas){
        var s= document.getElementById('<Element Id>');
        s.eampty();
        $.each(datas, function(index, el) {
            s.options[index]= new Option(index, el);
        });
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("error");
    }
});

dataType: "JSON",会以ajax格式回复json来电的输出。 将 <Element Id> 替换为您要添加数据的元素ID。

完整资源

<div class="form-group form-group-sm has-feedback <?php set_validation_style('Kota')?>">        
    <?php echo form_label('Kota / Kabupaten', 'kota', array('class' => 'control-label col-sm-2')) ?>
    <div class="col-sm-3">
       <?php
            $atribut_kota = 'class="form-control dropKota"';
            echo form_dropdown('Kota', $namaKota, $values->Kota, $atribut_kota);
            set_validation_icon('Kota');
        ?>
    </div>
    <?php if (form_error('Kota')) : ?>
        <div class="col-sm-9 col-sm-offset-3">
            <?php echo form_error('Kota', '<span class="help-block">', '</span>');?>
        </div>
    <?php endif ?>

    <script>
        $(document).ready(function () {
            $(".dropKota").select2({
                placeholder: "Pilih Kota"
            });
            $(".dropProv").on("change", function(){
                var idProv = $(this).val();
                var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
                var kota = [];
                $.ajax({
                    url: baseUrl,
                    data: kota,
                    dataType: "JSON",
                    success: function(datas){
                        var s= document.getElementById('<Element Id>');
                        s.eampty();
                        $.each(datas, function(index, el) {
                            s.options[index]= new Option(index, el);
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error");
                    }
                });
            });
        });
    </script>
</div>

答案 3 :(得分:0)

最后,我在问到这里之后找到了解决方案,所以这是解决方案:

JS和select2脚本

<script>
        $(document).ready(function () {
            $(".dropProv").on("change", function(){
                var idProv = $(this).val();
                var baseUrl = '<?php echo base_url(); ?>program/administrasi/registrasi/ajax_get_kota/'+idProv;
                var kota = [];
                $.ajax({
                    url: baseUrl,
                    dataType: 'json',
                    success: function(datas){
                        //since select2 need a specific format u need to do this
                        var kota = $.map(datas, function (obj) {
                            obj.id = obj.id || obj.id_kab; // replace id_kab with your identifier
                            obj.text = obj.text || obj.nama // replace nama with your identifier
                            return obj;
                        });
                        $(".dropKota").select2({ //change dropKota into your element
                            placeholder: "Pilih Kota",
                            data: kota
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("error");
                    }
                });
            });
        });
    </script>