Select2不加载远程数据 [英] Select2 not loading remote data
问题描述
我在select2上遇到了一些问题.我尝试通过遵循API文档来加载远程数据,但是我仍然得到一个加载指示器,没有错误,但是没有显示数据.
I'm having some issues with select2. I tried loading remote data by following API documentation, however I still get a load indicator, no errors, but no data is shown.
这是一些代码: https://gist.github.com/Fire-Dragon -DoL/5993136
Javascript:
(function() {
var $;
$ = jQuery;
$(function() {
$('a.submit-link').on('click', function(ev) {
ev.preventDefault();
$(this).closest('form').submit();
});
$('.spinner-float').spinner({
step: 0.01,
numberFormat: 'n',
min: 0
});
$('.spinner').spinner({
min: 0
});
$('.select2-cities').select2({
width: 200,
minimumInputLength: 1,
dropdownCssClass: 'bigdrop',
loadMorePadding: 300,
formatResult: function(obj, container, query, escapeMarkup) {
console.log("formatResult");
return obj.name;
},
formatSelection: function(obj, container) {
console.log("formatSelection");
return obj.name;
},
initSelection: function(element, callback) {
var id;
console.log("initSelection");
id = $(element).val();
if ((id != null) && id !== '') {
$.ajax(gon.cities_path + '/' + id + '.json', {
dataType: 'jsonp'
}).done(function(data) {
console.log("initSelection callback");
console.log(data);
callback(data);
});
}
},
ajax: {
url: gon.cities_path + '.json',
dataType: 'jsonp',
data: function(term, page) {
return {
query: term,
page: page - 1
};
},
results: function(data, page) {
console.log("results");
console.log(data);
return data;
}
}
});
});
}).call(this);
这是json响应:
{
"total": 8084,
"results": [
{
"cap": 35031,
"id": 8085,
"name": "Abano Terme",
"province": "PD",
"state_id": 25
},
{
"cap": 26834,
"id": 8086,
"name": "Abbadia Cerreto",
"province": "LO",
"state_id": 21
}
],
"more": false
}
然后是html的一部分(select2显示正确,我认为不是问题所在):
<!-- ... -->
<script type="text/javascript">
//<![CDATA[
window.gon = {};gon.cities_path="http://localhost:3000/cities";
//]]>
</script>
<!-- ... -->
<input class="select2-cities" id="travel_diary_city_id" name="travel_diary[city_id]" type="hidden" value="13987" />
在gist文件中,您还可以找到该代码的coffeescript版本.我真正不明白的是,无论如何都不会调用console.log
,因此基本上不会调用格式化功能和类似内容.
In the gist file you can also find the coffeescript version of the code. What I really don't understand is that console.log
is not called in any case, so basically formatting functions and similar things are not called.
更新1:解决了javascript代码的一些问题,其中一些键位于ajax对象而不是构造函数中.
Update 1: Solved some issues with javascript code where some keys were inside ajax object instead of the constructor.
推荐答案
好像我在使用JSONP
时未在服务器端实现它.将数据类型移动到json可以解决此问题.
Looks like I was using JSONP
while not implementing it server side. Moving data type to json fixed the issue.
这篇关于Select2不加载远程数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!