Select2 - 使用JSON作为本地数据 [英] Select2 - use JSON as local data
问题描述
我可以让它工作......
var options = [{id:1,text:'Adair, Charles'}]
$('#names')。select2({
data:options,
})
但我不知道如何从这里开始......
alert(JSON.stringify(request.names)) )给了我......
[{id:1,name:Adair,James} ,
{id:2,name:Anderson,Peter},
{id:3,name:Armstrong,Ryan}]
对于Select2将接受的东西作为本地数据
jquery-select2 ,示例包含一个演示使用 Select2
包含本地数据(数组) 。
html
< input type =hiddenid =e10style =width:300px/ >
javascript
$(document).ready(function(){
var sampleArray = [{id:0,text:'enhancement'},{id:1,text:'bug' }
,{id:2,text:'duplicate'},{id:3,text:'invalid'}
,{id:4,text:'wontfix'}];
$(#e10)。select2({data:sampleArray});
});
如果数组没有文本属性,则选择加载数据
对于您的问题,示例 e10_2
是相关的
< input type =hiddenid =e10_2style =width:300px/>
要实现您需要的功能 format()
如下所示:
$(document).ready(function(){
/ /告诉Select2使用文本
函数格式的属性名称(item){return item.name;};
var names = [{id:1,名字:Adair,James}
,{id:2,name:Anderson,Peter}
,{id:3,name :Armstrong,Ryan}]
$(#e10_2)。select2({
data:{results:names,text:'name'},
formatSelection :format,
formatResult:format
});
});
这是输出:
< img src =https://i.stack.imgur.com/coUSt.pngalt =Select2 - pimp my selectbox>
提示
要查看每个示例的源代码,最好使用chrome dev工具的网络选项卡,并在javascript启动之前查看html源代码。
I can get this to work...
var options = [{id: 1, text: 'Adair, Charles'}]
$('#names').select2({
data: options,
})
But i cant work out how to get from here...
alert(JSON.stringify(request.names)) gives me...
[{"id":"1","name":"Adair,James"},
{"id":"2","name":"Anderson,Peter"},
{"id":"3","name":"Armstrong,Ryan"}]
To something that Select2 will accept as local data
Load data from a local array
The webpage of jquery-select2 with the examples contains a demo to use Select2
with local data (an array).
The html
<input type="hidden" id="e10" style="width:300px"/>
The javascript
$(document).ready(function() {
var sampleArray = [{id:0,text:'enhancement'}, {id:1,text:'bug'}
,{id:2,text:'duplicate'},{id:3,text:'invalid'}
,{id:4,text:'wontfix'}];
$("#e10").select2({ data: sampleArray });
});
Select2 load data if array has no text property
For your question the example e10_2
is relevant
<input type="hidden" id="e10_2" style="width:300px"/>
To achive that you need the function format()
as seen below:
$(document).ready(function() {
// tell Select2 to use the property name for the text
function format(item) { return item.name; };
var names = [{"id":"1","name":"Adair,James"}
, {"id":"2","name":"Anderson,Peter"}
, {"id":"3","name":"Armstrong,Ryan"}]
$("#e10_2").select2({
data:{ results: names, text: 'name' },
formatSelection: format,
formatResult: format
});
});
This is the output:
Hint
To see the source code of each example it is best to use the network tab of the chrome dev tools and take a look of the html source before javascript kicks in.
这篇关于Select2 - 使用JSON作为本地数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!