我正在使用select2来显示动态名称列表。当用户输入时,通过相似性从服务器获取名称,但是如果找不到名称,我会显示一个“建议”链接,将名称添加到数据库中。
“建议”链接出现在选择的通知区域中(查询服务器时出现“正在搜索...”)。当用户按下“建议”时,如上所述,请求将建议的名称添加到数据库中。现在,当该请求响应时,我希望将名称添加到select2的列表中,选中,并关闭下拉框。
我在这项努力中没有取得任何成功=)我尝试使用'val',但我要么做得不对,要么就是不行。这是我现在所拥有的代码摘录:
$('.' + id + '-select2', nextFrame).select2({
ajax: {
url: url,
dataType: 'json',
results: function(data) {
var results = [], it;
for (it in data) {
results.push({
id: data[it]['pid'],
text: data[it]['name']
});
}
return { results: results }
},
data: function(text) {
return { name: text }
}
},
formatNoMatches: function(text) {
// Add the AJAX behavior to the anchor, but do it asynchronously
// This way we give time to select2 to render the layout before we configure it
setTimeout(function() {
$('#' + id + '-ajax-anchor').on('click', function(e) {
var target = $(e.target);
$.ajax({
url: target.attr('href'),
type: 'POST',
dataType: 'json',
data: {
name: text
},
})
.done(function(response) {
/*
Need help here !!
1) Add the response to the list
2) Select it
3) Close
*/
})
;
e.preventDefault();
});
}, 1);
return "No match, <a id='" + id + "-ajax-anchor' href='" + url + "'>suggest</a>";
},
});
答案 0 :(得分:2)
只需在代码的帮助下修复它。这是我的done()
部分:
done(function(resp) {
d = $(s2).select2("data"); // s2 is this select2 object. in your case $('.' + id + '-select2', nextFrame);
$(s2).select2("close"); // first close the opened list. select2 doesn't close "result not found".
d.push({id: resp.id, title: resp.title}); // now add ajax response to our current select2 data. in my case response contains count, id and title of the added/suggested
$(s2).select2("data", d);
});
答案 1 :(得分:-1)
//...
.done(function (response) {
var myValue = response.value;
var myText = response.text;
var o = new Option(myText, myValue);
$(o).html(myText);
$("select").append(o);
$("select option[value='" + myValue + "']").attr('selected', 'selected');
})
//...