select2从json获取数据

问题描述 投票:0回答:2

问候,我正在使用ajax请求填充我的select2选择字段,但是从api多次查询对性能效率不高,我已经有一个存储我所有json数据的变量。我只是不知道如何用AJAX中的url请求替换它

下面是我的代码:

    // The all_project that contain my json data
    var all_project_json = $.ajax({
        type: "GET",
        url: "/api/dashboard/report/?format=json",
        dataType: "application/json",
        async: false
    }).responseText;
    var all_project = JSON.parse(all_project_json);

    // Project Type Filter
    $('#project_type_select2').select2({
        placeholder: "Select type",
        //I want to replace the ajax request from getting the data from URL
        to getting the data from the all_project variable
        ajax: {
            url: '/api/dashboard/report/?format=json',
            type: 'GET',
            data: function (params) {
                var query = {
                    search: params.term,
                    type: 'public'
                }
            return {  }
            },
            processResults: function (data) {
                var project_type_list= []
                var project_type_option = [{"id": "all", "text": "All"}]
                for(i = 0; i < data.length; i++){
                    project_type_list.push(data[i].project_type)
                }
                project_type_unique = $.unique(project_type_list);
                for(i = 0; i < project_type_unique.length; i++){
                    project_type_option.push({"id": i, "text": project_type_unique[i]})
                }
                return {
                    results: project_type_option,
                };
            } 
        }
    });

任何帮助非常感谢谢谢。

jquery json ajax jquery-select2
2个回答
0
投票

您可以使用select2 data属性而不是ajax并传递您的数据:

// Your all_project array contains all data after ajax call..
var data= $.map(all_project, function(obj) {
              return { search: obj.term, type: 'public' } };
          });

$('#project_type_select2').select2({
        placeholder: "Select type",
        data: data
        //... whatever..
});

0
投票

找到解决方案:

var all_project_json = $.ajax({
    type: "GET",
    url: "/api/dashboard/report/?format=json",
    dataType: "application/json",
    async: false
}).responseText;
var all_project = JSON.parse(all_project_json);

// Project Type Filter
var project_type_list= []
var project_type_option = [{"id": "all", "text": "All"}]
for(i = 0; i < all_project.length; i++){
    project_type_list.push(all_project[i].project_type)
}
project_type_unique = $.unique(project_type_list);
for(i = 0; i < project_type_unique.length; i++){
    project_type_option.push({"id": i, "text": project_type_unique[i]})
};
$('#project_type_select2').select2({
    placeholder: "Select type",
    data: project_type_option,
});
© www.soinside.com 2019 - 2024. All rights reserved.