无法在 codeigniter 中加载 select 2 jquery ajax 中的数据

Cannot load data in select 2 jquery ajax in codeigniter

我想在 select2 中使用 ajax 在搜索字段中的文本更改中加载数据,我正在使用以下代码但它不是 working.There 在控制台中没有错误并且 jquery 函数未被调用。

jQuery('#t_name').select2({
  ajax: {
    url: 'get-all_data',
    processResults: function (data) {
      return {
            text: item.text,
                        id: item.id
      };
    }
  }
});

public function getAllData()
    {
        $json = [];
        $results=$this->db->select('*')->from($this->user)->get()->result_array();
        foreach($results as $row)
        {
        $json[] = ['id'=>$row['id'], 'text'=>$row['name']];
        }
        return $json;  

    }

请尝试在您的 ajax url 中添加 base_url 项目:

    jQuery('#t_name').select2({
      ajax: {
        url: base_url + 'get-all_data',
        processResults: function (data) {
          return {
                text: item.text,
                            id: item.id
          };
        }
      }
    });

您应该尝试以下操作:

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

对于使用 ajax 的 select2,需要 JSON 格式的数据,并且您在 processResults.

中输入错误

请检查以下代码。

$('.js-data-example-ajax').select2({
    ajax: {
        url: 'get-all_data',
        dataType: 'json',
        processResults: function (data) {
            return {
                results: data
            }
        }
    }
});

PHP代码

public function getAllData()
{
    $json = [];
    $results=$this->db->select('*')->from($this->user)->get()->result_array();
    foreach($results as $row)
    {
        $json[] = ['id'=>$row['id'], 'text'=>$row['name']];
    }
    echo json_encode($json);
}

更新

建议:另外,您可以在PHP函数中使用这段代码,不需要使用for循环来设置日期。

public function getAllData() {
    $results = $this->db->select('id, name as text')->from($this->user)->get()->result_array();
    echo json_encode($results);
}

试试这个

在你的控制器中

public function getAllData()
{
    //if( $this->input->get('q') != '' ){do something}

    $json = [];
    $results=$this->db->select('*')->from($this->user)->get()->result_array();
    foreach($results as $row)
    {
        $json[] = ['id'=>$row['id'], 'text'=>$row['name']];
    }

    header('Content-Type: application/json');
    header('Pragma: no-cache');
    header('Cache-Control: no-store, no-cache');
    echo json_encode( $json );

}

在你的javascript

$(document).ready(function(){

$(".select2").select2({
            minimumInputLength: 2,
            ajax: {
                url: '<?=base_url()?>/get-all_data',
                dataType: 'json',
                delay: 250,
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                cache: false
            }
        });

});