Select2 内置了对 AJAX 的支持,使用的是 jQuery 的 AJAX 方法。在这个例子中,我们可以使用 GitHub 的 API 来搜索代码仓库:
在你的 HTML 中:
<select class="js-data-example-ajax"></select>
在你的 Javascript 中:
$('.js-data-example-ajax').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json'
// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
}
});
你可以通过配置ajax
选项来设置 Select2 如何搜索远程数据。ajax
Select2 会将$.ajax
对象中的任何选项传递给 jQuery 的transport
函数,或者你指定的函数。
对于远程数据源,Select2 不会在条目首次被选中之前创建新的
<option>
元素。<option>
一旦一个
当用户打开控件时(除非有一个值被设置为 Select2 的选项),以及每次用户在搜索框输入内容时,Select2 将向指定的 URL 发起请求。默认情况下,它会作为查询字符串参数发送以下内容:minimumInputLength
set as a Select2 option), and again every time the user types in the search box. By default, it will send the following as query string parameters:
term
term:当前在搜索框中的搜索关键词。q
q:包含与term
._type
type:一种“请求类型”。通常是query
,但对于分页请求则会变为query_append
page:请求的当前页码。仅用于分页(无限滚动)搜索时发送。page
例如,Select2 可能发出如下请求:有时,你可能需要向请求中添加额外的查询参数。你可以通过重写https://api.github.com/search/repositories?term=sel&_type=query&q=sel
.
Sometimes, you may need to add additional query parameters to the request. You can modify the parameters that are sent with the request by overriding the ajax.data
选项下的选项:
$('#mySelect2').select2({
ajax: {
url: 'https://api.github.com/orgs/select2/repos',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
你可以使用ajax.processResults
选项将你的 API 返回的数据转换为 Select2 所期望的格式:
$('#mySelect2').select2({
ajax: {
url: '/example/api',
processResults: function (data) {
// Transforms the top-level key of the response object from 'items' to 'results'
return {
results: data.items
};
}
}
});
Select2 期望远程端点的结果已经在服务端进行过筛选。此评论解释了为何做出此实现选择。如果不能进行服务端筛选,你可以考虑使用 Select2 的数组形式数据支持代替。
你可能希望为从 AJAX 请求获取数据的 Select2 控件设置一个预选的默认值。
要提供默认选择,可以为每个选择包含一个<option>
,其中包含应显示的值和文本:
<select class="js-example-data-ajax form-control">
<option value="3620194" selected="selected">select2/select2</option>
</select>
如果要以编程方式实现这一点,你需要创建并附加一个新的Option
.
Select2 开箱即用地支持远程数据源的分页(“无限滚动”)。要使用这个功能,你的远程数据源必须能够处理分页请求(像Laravel和UserFrosting这样的服务端框架内置了该功能)。
要使用分页,你必须通过重写ajax.data
设置告诉 Select2 添加必要的分页参数到请求中。当前要获取的页码存储在params.page
属性中。
$('#mySelect2').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
// Query parameters will be ?search=[term]&page=[page]
return query;
}
}
});
Select2 期望在响应中找到一个pagination.more
值。该more
值应该为true
或false
,这告诉 Select2 是否还有更多的结果页可供检索:
{
"results": [
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
],
"pagination": {
"more": true
}
}
如果你的服务端代码没有在响应中生成pagination.more
属性,你可以使用processResults
从其他可用信息中生成此值。例如,假设你的 API 返回了一个count_filtered
值,告诉你整个数据集中一共有多少个(未分页)结果。如果你知道你的分页 API 每次返回 10 个结果,你可以将该值和count_filtered
的值结合起来计算出pagination.more
:
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.results,
pagination: {
more: (params.page * 10) < data.count_filtered
}
};
}
你可以告诉 Select2 等待用户完成输入搜索词后再触发 AJAX 请求。只需使用ajax.delay
配置选项告诉 Select2 用户停止输入后等待多久才发送请求:
$('#mySelect2').select2({
ajax: {
delay: 250 // wait 250 milliseconds before triggering the request
}
});
如果你的搜索结果没有单一的 URL,或者你需要调用某个函数来确定使用的 URL,你可以为ajax.url
选项指定一个回调函数来生成 URL。当前的搜索查询会通过params
选项下的选项:
$('#mySelect2').select2({
ajax: {
url: function (params) {
return '/some/url/' + params.term;
}
}
});
Select2 使用定义在ajax.transport
中的传输方法将请求发送到你的 API。默认情况下,这种传输方法是jQuery.ajax
,但可以轻松地被覆盖:
$('#mySelect2').select2({
ajax: {
transport: function (params, success, failure) {
var request = new AjaxRequest(params.url, params);
request.on('success', success);
request.on('failure', failure);
}
}
});
$.ajax
选项所有传递给ajax
的选项都将直接传递给执行 AJAX 请求的$.ajax
函数。
有一些自定义选项会被 Select2 截取,允许你在请求发出时对其进行自定义:
ajax: {
// The number of milliseconds to wait for the user to stop typing before
// issuing the ajax request.
delay: 250,
// You can craft a custom url based on the parameters that are passed into the
// request. This is useful if you are using a framework which has
// JavaScript-based functions for generating the urls to make requests to.
//
// @param params The object containing the parameters used to generate the
// request.
// @returns The url that the request should be made to.
url: function (params) {
return UrlGenerator.Random();
},
// You can pass custom data into the request based on the parameters used to
// make the request. For `GET` requests, the default method, these are the
// query parameters that are appended to the url. For `POST` requests, this
// is the form data that will be passed into the request. For other requests,
// the data returned from here should be customized based on what jQuery and
// your server are expecting.
//
// @param params The object containing the parameters used to generate the
// request.
// @returns Data to be directly passed into the request.
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
// You can modify the results that are returned from the server, allowing you
// to make last-minute changes to the data, or find the correct part of the
// response to pass to Select2. Keep in mind that results should be passed as
// an array of objects.
//
// @param data The data as it is returned directly by jQuery.
// @returns An object containing the results data as well as any required
// metadata that is used by plugins. The object should contain an array of
// data objects as the `results` key.
processResults: function (data) {
return {
results: data
};
},
// You can use a custom AJAX transport function if you do not want to use the
// default one provided by jQuery.
//
// @param params The object containing the parameters used to generate the
// request.
// @param success A callback function that takes `data`, the results from the
// request.
// @param failure A callback function that indicates that the request could
// not be completed.
// @returns An object that has an `abort` function that can be called to abort
// the request if needed.
transport: function (params, success, failure) {
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
此代码驱动了本章开头所展示的 Github 示例: