[英]Ajax select2 example
I'm needing to download names of cities in a comboBox Select2 via ajax, but so far it has not worked. 我需要通过ajax在comboBox Select2中下载城市名称,但是到目前为止,它没有用。 many examples in internet search, but not understand them too.
互联网搜索中有很多示例,但也不太了解。
$(document).ready(function() {
var url = "http://localhost:8000/api/city?";
$("#city").select2({
minimumInputLength: 1,
ajax: {
url: url,
dataType: 'json',
type: "GET",
delay: 500,
data: function (term) {
return {
city: term
};
},
results: function (data) {
console.log(data);
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
});
y este es el código json que devuelve mi servidor con la consulta realizada: 由est es elcódigojson到devuelve mi servidor con la consultanta realizada:
[{ "id": 1, "text": "Capital, Córdoba, Argentina" }]
Dice "Searching...." y luego "No results found" 骰子“正在搜索...。”和luego“未找到结果”
Really, Thanks! 真的感谢!
First of all if you are using Select2 version 4+, make sure you initialize select2() on a <select>
element or many of his feature like AJAX will be turned off. 首先,如果您使用的是Select2版本4+,请确保在
<select>
元素上初始化select2(),否则他的许多功能(例如AJAX)都将关闭。
Select2 will need a formated answer from your server at : http://localhost:8000/api/city?
Select2将需要来自服务器的格式化答案:
http://localhost:8000/api/city?
Response returned by your server should look like this: 服务器返回的响应应如下所示:
[
{id:1,text:'city1'},
{id:2,text:'city2'},
]
The options: minimumInputLength = 0
, will make it load the whole list on click minimumResultsForSearch
, control how many results you need to display the search box into select2 list. 选项:
minimumInputLength = 0
,将使其在单击minimumResultsForSearch
时加载整个列表,控制将搜索框显示到select2列表中需要多少个结果。
ajax{data: function(param)}
is the function called to format the user data into something your server will understand, what you return here is send to your {ajax:url}
ajax{data: function(param)}
是用于将用户数据格式化为服务器可以理解的格式的函数,您在此处返回的内容将发送到{ajax:url}
ajax{processResults: function (data, status)}
, this is called when you ajax got a successful response from your server , data
will be the response from your server this is the last chance you have to make sure that data
is formated like select2 need , see top of this post. ajax{processResults: function (data, status)}
,当ajax从服务器成功获得响应时调用此方法, data
将是服务器的响应,这是您必须确保data
的格式类似于select2的最后一次机会需要,请参阅本文顶部。 What you return here is send to select2. 您在此处返回的内容将发送到select2。
Hope it help! 希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.