我正在尝试按照此示例使用 select2 实现 ajax 调用: https ://github.com/genemu/GenemuFormBundle/blob/master/Resources/doc/jquery/select2/ajax.md
这是我的代码:
var $configs = {{ configs|json_encode|raw }};
$field = $('#{{ id }}');
$configs = $.extend($configs, {
ajax: {
id: function (friend) { return friend.username; },
url: $field.data('url'),
data: function (term, page) {
return { q: term, page_limit: 10, page: page };
},
results: function (data, page) {
var more = (page * 10) < data.total;
return { results: data, more: more };
}
},
formatResult: function (friend) {
var markup = "<div class='friend-results-box'>";
if (friend.avatar !== undefined) {
markup += "<img width='60' height='75' src='" + friend.avatar + "'/>";
}
markup += "<h5>" + friend.username + "</h5>";
markup += "<div class'clearfix'></div>";
markup += "</div>";
return markup;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text'); // ?
callback({"term":elementText});
},
formatSelection: function (friend) { return friend.username; },
escapeMarkup: function (m) { return m; },
dropdownCssClass: "dropdown-friends"
});
$field.select2($configs);
现在我的问题是:
- 当我的意图是从 json 中获取的值被定义为friend.username 时,值正在用 ID 填充
- 页面重新加载后初始值没有显示在屏幕上(因为值被设置为 ID)并且 select2 没有选择它
任何提示或帮助将不胜感激!