首页 > 解决方案 > Make correct json data format for select2

问题描述

i am trying to ajax remote data for select2(using 4.0.6-rc.1), tried a few examples, at first the q parameter was undefined but i solved it and now the select is not giving me the results,don't know how to format the json data tried the following and getting the following error in the console:

$('#compose_username').select2({
    dropdownParent: $("#modal-compose"),
    placeholder: "Search country here...",
    ajax: {
        url: "username.php",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data, params) {
            params.page = params.page || 1;
            return {
                results: data.items,
                pagination: {
                    more: (params.page * 30) < data.total_count
                }
            };
        },
        cache: false
    },
    // escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 1,
    templateResult: formatRepo,
    templateSelection: formatRepoSelection
});

function formatRepo(repo) {
    if (repo.loading) return repo.text;

    return repo.desc;
}

function formatRepoSelection(repo) {
    return repo.desc || repo.text;
}

USERNAME.PHP

include('../core/config.php');

try {
    $stmt = $db_con->query("SELECT id,username FROM users WHERE username LIKE '%".$_GET['q']."%' LIMIT 10");
    $stmt->execute();
    $json = [];

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $json[] = ['id'=>$row['id'], 'username'=>$row['username']];
    }

    echo json_encode($json);
} catch(PDOException $e) {
    echo $e->getMessage();
}

JSON DATA:

if i type a then getting the following in console but no option is showing in select2

(3) [{…}, {…}, {…}]
0
:
{id: "1", username: "admin"}
1
:
{id: "29", username: "adil3310"}
2
:
{id: "30", username: "asdsad"}
length
:
3
__proto__
:
Array(0)

标签: javascriptphpjsonajaxjquery-select2

解决方案


经过一番努力,我设法让它工作,我试图解析 Json 数据并且它已经被解析的原因,所以我使用它并且它工作。下面的完整工作示例,可能对其他人有所帮助:

  $('#compose_username').select2({
        // SET THIS IF SELECT IS IN A MODAL
        dropdownParent: $("#modal-compose") ,
        placeholder: "Search country here...",
       // MINIMUM INPUT TO SEARCH BEFORE
        minimumInputLength: 3,
        ajax: {
            url: "username.php",
            dataType: 'json',
            delay: 250,
            cache: false,
            data: function (params) {
                $('#compose_username').val(null).trigger('change');
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function(data, page) {
                console.log(data);
                var result = $.map(data, function (item) { return { id: item.id, text: item.username }});
                return { results: result };
            }
        }
  });

PHP( FOR GETTING LIST OF USERNAME, 我们可以在查询中设置限制)

try{
    $stmt = $db_con->query("SELECT id,username FROM users WHERE username LIKE '%".$_GET['q']."%' LIMIT 10");
    $stmt->execute();
        $json = [];
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
             $json[] = ['id'=>$row['id'], 'username'=>$row['username']];
        }
        echo json_encode($json);
}
catch(PDOException $e){
    echo $e->getMessage();
}

推荐阅读