问题
I have a problem to set the method initSelection with an ajax call, I returns "undefined". I checked and the ajax call returns the correct result .. I donot understand the method how to set the callback method to make sure that you select 'the preset value.
function mediaFormatResult(media) {
var markup = "<div class='media-title'>" + media.name + ", " + media.prov + " (" + media.region + ")</div>";
return markup;
}
function mediaFormatSelection(media) {
return media.name +", " + media.prov + " (" + media.region + ")";
}
$field = $('#comune');
$($field).select2({
placeholder: "Seleziona il tuo comune",
minimumInputLength: 3,
initSelection: function(element, callback) {
return $.ajax({
type: "POST",
url: "myurl",
dataType: 'json',
data: { id: (element.val())},
success: function(data){
//results: data.results;
}
}).done(function(data) {
//console.log(data);
callback(data);
});
},
ajax: {
quietMillis: 100,
url: "myurl",
dataType: 'json',
type: 'POST',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return {results: data.results};
}
},
formatResult: mediaFormatResult,
formatSelection: mediaFormatSelection,
formatNoMatches: function () { return "Nessun risultato trovato!";},
formatSearching: function () { return "Ricerco.."; },
formatInputTooShort: function(input, min) {return "Inserire "+ (min - input.length) + " caratteri.";},
dropdownCssClass: "bigdrop",
});
There is something wrong?
回答1:
Pay attention, the data you send to the callback function, needs to be an object, with an id and text attributes.
This is what worked for me:
initSelection: function(element, callback) {
var id;
id = $(element).val();
if (id !== "") {
return $.ajax({
url: url,
type: "POST",
dataType: "json",
data: {
id: id
}
}).done(function(data) {
var results;
results = [];
results.push({
id: data.id,
text: data.name
});
callback(results[0]);
});
}
}
回答2:
Here the way to solve:
initSelection: function(element, callback) {
return $.ajax({
type: "POST",
url: path,
dataType: 'json',
data: { id: (element.val())},
success: function(data){
}
})
care must be taken that the array is created in the controller and it should be something like this:
foreach ($entities as $member) {
$json['id'] = $member->getId();
$json['name'] = $member->getComune();
$json['region'] = $member->getRegione()->getRegione();
$json['prov'] = $member->getProvincia()->getSigla();
}
$result = $json;
return json_encode($result);
来源:https://stackoverflow.com/questions/15112988/select2-initselection