Select2不显示来自AJAX的结果

时间:2018-10-22 07:44:02

标签: jquery ajax jquery-select2

为什么我的select2对象在过滤时始终显示“未找到结果”,但是当我在Google Chrome上检查网络时,它会做出响应。我正在使用select2版本。 4.0.6-rc.1

Select2

这是我创建select2 obj的代码:

<div class="form-group" id="divjualcust">
    <label>Customer</label>
    <select class="js-example-basic-single" name="customer" id="jualcust" style="width:100%"></select>
    <label id="lblerrjual" style="display:none"><i>*sudah terdaftar</i></label>
</div>

javascript代码:

$(document).ready(function() {
    $("#jualcust").select2({
        ajax: {
            url: "controller/customer_list.php",
            dataType: "json",
            type:"GET",
            delay: 250,
            data: function (params) {
                return {
                    search: params.term
                }
            },
            processResults: function (data) {
                // parse the results into the format expected by Select2.
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data
                return {
                    results: $.map(data.items, function (item) {
                      return {
                        id:item.id,
                        text:item.text
                      }
                    })
                };
            },
            cache: false
        },
        minimumInputLength: 3,
    });

这是我的controller/customer_list.php上的函数:

function getCustList($search) {
    //declare var public
    $cn=new Database();
    $cust=array();
    $row=$cn->getAll("select cust_id, concat(cust_kode,' - ',cust_nama) as custnama from t_customer 
                      where concat(cust_kode,' - ',cust_nama) like '%$search%' order by concat(cust_kode,' - ',cust_nama)");
    if (is_array($row)) {
        foreach ($row as $dt) {
            $id=$dt["cust_id"];
            $text=$dt["custnama"];
            $cust[]=array("id"=>$id,"text"=>$text);
        }
        echo json_encode($cust);
    }
}

1 个答案:

答案 0 :(得分:0)

您没有items数组,因此只需要在data上循环

results: $.map(data, function (item) {
                      return {
                        id:item.id,
                        text:item.text
                      }
                    })