我有如下代码:
var locations = [
<?php foreach($locations as $loc) {echo '{ id: ' . $loc['id'] . ', text: "' . $loc['name'] . '" },';} ?>
];
$("#location-id").select2({
data: locations,
placeholder: '<?= lang("hol") ?>?',
allowClear: true,
minimumInputLength: 3,
});
位置数组有将近10000个元素,在加载它时浏览器会冻结几秒钟,特别是当我有更多这样的选择框时,所以我想我需要一些自定义查询或AJAX函数来避免将整个数组加载到select 2中。我在互联网上发现的东西已经过时了,无法适用于新的select 2 4.0.3版本。在select 2主页上,有一个Ajax示例代码,我认为它可以做我需要做的事情,但是使用远程数据:
$(".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
});
所以我需要适用本地数据。
有人能让select2不加载整个数组吗?