Select2和initSelection回调 [英] Select2 and initSelection callback
问题描述
在页面加载时,我尝试使用initSelection选择ID 60 (输入字段的指定值).我似乎无法使其正常工作.
On page load, I'm trying to use initSelection to select ID 60 (specified value of the input field). I can't seem to get it to work properly.
PHP脚本可以很好地工作并返回正确的值,但是如何获取JS才能正确执行回调?
The PHP scripts work great and return the correct values, but how do I get the JS to do the callback correctly?
JavaScript:
$(document).ready(function() {
$('#editAlbumArtistId').select2({
placeholder: 'Search names',
ajax: {
url: "/jQueryScripts/jQuerySelectListArtists.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return {results: data.results};
}
},
initSelection: function(element, callback) {
var id = $(element).val();
if(id !== "") {
$.ajax("/jQueryScripts/jQuerySelectListArtists.php", {
data: {id: id},
dataType: "json"
}).done(function(data) {
callback(data);
});
}
}
});
});
HTML:
<p>
<input type='hidden' value="60" data-init-text='Search names' name='editAlbumArtistId' id='editAlbumArtistId' style="width:180px;"/>
</p>
每次刷新页面时,都会看到PHP脚本得到执行,并且返回正确的ID和文本.但是,该字段没有更新,我已经认真尝试了我能想到的一切.
Every time I refresh the page, I see that the PHP script gets executed and that it returns the proper ID and text. However, the field isn't updated and I've seriously tried everything I can think of.
我正在使用Select2 3.4.3.
I'm using Select2 3.4.3.
任何帮助将不胜感激.
推荐答案
终于解决了!我发现select2
不需要数组,因为它是单个值,所以我选择了data.results数组的第一个元素.
Finally solved it! I figured select2
didn't want an array since it's a single value, so I selected the first element of the data.results array.
callback(data.results[0]);
如果您设置了multiple:true,则只需接受整个结果数组;
And if you have set multiple:true, just accept the entire results array;
callback(data.results);
这篇关于Select2和initSelection回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!