问候,我正在使用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,
};
}
}
});
感谢任何帮助。
答案 0 :(得分: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..
});
答案 1 :(得分: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,
});