# 数据源
# 格式
{
"results": [
{
"id": 1,
"text": "Option 1",
"selected": true
},
{
"id": 2,
"text": "Option 2",
"disabled": true
},
{
"id": 3,
"text": "Option 3"
}
],
"pagination": {
"more": true
}
}
# Arrays
var data = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 2,
text: 'duplicate'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
$('.js-example-basic-single').select2({
data: data,
width: '10%'
});
# Ajax
$('.js-data-example-ajax').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json',
delay: 250,
data: function (params) {
var query = {
q: params.term,
page: params.page || 1,
per_page: 10
}
return query;
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 10) < data.total_count
}
};
},
cache: false
},
width: '300',
placeholder: 'Search for a repository',
minimumInputLength: 1,
templateResult: function (repo) {
return repo.full_name || repo.text;
},
templateSelection: function (repo) {
return repo.full_name || repo.text;
}
});