Javascript 如何在使用ajax时向select2动态添加元素
我正在使用select2显示一个动态的姓名列表。根据相似性,这些名称是在用户键入时从服务器获取的,但如果找不到名称,我会显示一个建议链接,将名称添加到数据库中 “建议”链接出现在“选择”的通知区域中,其中搜索。。。查询服务器时显示。当用户按“建议”时,会发出一个请求,如前所述,将建议的名称添加到数据库中。现在,当该请求响应时,我希望将该名称添加到select2的列表中,并选中,然后关闭下拉框 我在这项努力中没有取得任何成功=我尝试使用“val”,但我要么做得不对,要么就不是这样。下面是我现在拥有的代码摘录:Javascript 如何在使用ajax时向select2动态添加元素,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我正在使用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>";
},
});
只是在你的代码帮助下修复了它。以下是我已完成的部分:
它不起作用。。。Select2用一个div和一个ul列表替换select元素,我尝试使您的解决方案适应这个事实,但没有成功。这是很久以前的事了=但该代码有效吗?如果是的话,我会接受答案。是的,你的代码对我很有帮助。我刚刚使用select2实现了一个标签选择组件,可以远程添加新标签。我很高兴=如果我没记错的话,我当时也解决了这个问题,但我想我忘了在这里发布它。我接受你的回答。
//...
.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');
})
//...
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);
});