【发布时间】:2013-08-13 03:19:11
【问题描述】:
我正在使用 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>";
},
});
【问题讨论】:
标签: javascript jquery jquery-select2