【发布时间】:2017-02-13 12:31:28
【问题描述】:
在 Select2 中,我想选择一个选项 india。我开始在选择框中输入两个字母in。之后,我想通过jQuery从数据库中加载选项标签中的相关数据。我该怎么做?
【问题讨论】:
标签: jquery jquery-plugins select2
在 Select2 中,我想选择一个选项 india。我开始在选择框中输入两个字母in。之后,我想通过jQuery从数据库中加载选项标签中的相关数据。我该怎么做?
【问题讨论】:
标签: jquery jquery-plugins select2
对于您的示例,您可以查找此解决方案:http://jqueryui.com/autocomplete/
除此之外,您还可以使用 Jquery 自动完成功能。
除此之外,您还可以编写自己的函数,该函数将在输入文本的 keydown 时将选择查询发送到您的数据库,并获取相关列表以附加到选择框中。
【讨论】:
您是否使用 2 个 select2 下拉菜单?如果是,那么在更改第一个选择下拉列表时,您将使用 AJAX 获取相关数据并将其加载到您的目标 select2 下拉列表中,将结果对象作为“数据”属性传递,同时为其初始化 select2。
如果这不是您想要的,请详细说明您的问题。
【讨论】:
我想出了解决方案@https://select2.github.io/examples.html#data-ajax。
HTML 部分:
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
JQUERY 部分:
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
【讨论】: