问题
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.
Here is some code: 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);
And here is the json response:
{
"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
}
And a part of the html (select2 is showing correctly, I don't think that's the issue):
<!-- ... -->
<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" />
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.
Update 1: Solved some issues with javascript code where some keys were inside ajax object instead of the constructor.
回答1:
Looks like I was using JSONP
while not implementing it server side. Moving data type to json fixed the issue.
来源:https://stackoverflow.com/questions/17636385/select2-not-loading-remote-data