gpt4 book ai didi

javascript - 使用ajax时如何动态添加元素到select2

转载 作者:行者123 更新时间:2023-11-29 15:41:32 25 4
gpt4 key购买 nike

我正在使用 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>";
},
});

最佳答案

刚刚在您的代码帮助下修复了它。这是我的 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);
});

关于javascript - 使用ajax时如何动态添加元素到select2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18200115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com