select2 期望从服务器获得什么数据结构,应该如何处理?
What data structure is select2 expecting from the server and how should it be handled?
select2 (v4.0.3) 期望服务器提供什么数据结构,应该如何处理?
在官方FAQhere上提出了问题,但没有答案。
我已经尝试了多种数据结构变体,但基于此 tutorial and this jsFiddle,我假设应该从服务器返回的是 objects/dicts 的 list/array,例如:
matches = [{"id":"1", "tag":"Python"},{"id":"2", "tag":"Javascript"},{"id":"3", "tag":"MongoDB"}]
我已经用下面的格式尝试过这种格式 Javascript:
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data.matches
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});
Firebug Py
的搜索结果:
搜索区只显示这个:
我希望所有匹配项都显示在搜索区域下方的下拉列表中。
对我有用的解决方案:
重命名 json 键(必须是 text
),所以服务器响应是:
[{"text": "Python", "id": 1}]
(遇到this document之后)。
我也只是从服务器返回了列表本身,而不是将列表作为字典值。
Javascript
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});
select2 (v4.0.3) 期望服务器提供什么数据结构,应该如何处理?
在官方FAQhere上提出了问题,但没有答案。
我已经尝试了多种数据结构变体,但基于此 tutorial and this jsFiddle,我假设应该从服务器返回的是 objects/dicts 的 list/array,例如:
matches = [{"id":"1", "tag":"Python"},{"id":"2", "tag":"Javascript"},{"id":"3", "tag":"MongoDB"}]
我已经用下面的格式尝试过这种格式 Javascript:
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data.matches
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});
Firebug Py
的搜索结果:
搜索区只显示这个:
我希望所有匹配项都显示在搜索区域下方的下拉列表中。
对我有用的解决方案:
重命名 json 键(必须是 text
),所以服务器响应是:
[{"text": "Python", "id": 1}]
(遇到this document之后)。
我也只是从服务器返回了列表本身,而不是将列表作为字典值。
Javascript
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});