我使用select2作为标记输入,但是在处理新标记的创建和将新标记id重新放回select2
时我感到困惑这个问题与Select2.js: why is id the same as text on change for removed?
密切相关你可以从他的jsfiddle http://jsfiddle.net/7e8Pa/看到,当在createSearchChoice中找不到文本时,会创建新选项,id:-1,text:term,然后在on change事件中,将id更改为5
我需要能够向服务器提交$.post
,并获取ID而不是使用静态5
问题是,如果我在createsearchoption中提交帖子,那么在标签tabe中找不到的每个击键都会创建一个新标签,并且在on change事件中尝试发布,我假设更改事件在ajax返回之前结束< / p>
.on("change", function(e) {
log("change "+JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
if (e.added) { // if its got an add obj
if (isNumeric(e.added.id)){
//if its not an existing tag , it passes a string instead of an id
// so just do a regular add
add(e.added.id);
} else {
//get the term text, post to server, return the new tag id
$.post('handlers/tags.ashx',
{ operation:"select2createtag",
text: $.trim(e.added.id.substring(3, e.added.id.length))} ,
function(data){
add(data.id);
});
};
答案 0 :(得分:0)
我最终做的是使用createsearchchoice函数,并且在返回期间我将id指定为连接-1和术语,文本(以及不必要的附加变量)
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
// call $.post() to add this term to the server, receive back id
// return {id:id, text:term}
// or detect this shiftiness and do it below in the on-change
return {
id: -1+'/'+term,
text: $.trim(term) + ' (new tag)'
, isNew: true
};
},
然后,在我的onchange函数中,如果添加,我评估id;如果它存在,它将具有数字ID,如果不存在,则表示它是使用createsearchchoice连接创建的
我发送一个帖子到我的服务器来创建该标签,通过从id中对新标签进行子标记(对于正则表达式更好,但我离题了),并且该帖子返回一个标签ID,然后我可以在单独的帖子来标记项目
.on("change", function(e) {
if (e.added) {
if (isNumeric(e.added.id)){
add(e.added.id);
} else {
$.post('handlers/tags.ashx', {
operation:"select2createtag",
text: $.trim(e.added.id.substring(3, e.added.id.length))} ,
function(data){
//sql returns a new id for the newly created tag
e.added.id = data.id;
add(data.id); // see add function
});
};
};
这是添加功能
function add(tagid){
///takes a tag id and inserts it in the relational table between item and tag
$.ajax({
url: "handlers/tags.ashx",
dataType: "json",
data: {
idnumber: entity_id,
proposalid: proposal_id,
tag: tagid,
operation:"select2tag"
}
}).done(function(data){
if(data.result == false){
alert('tag was not inserted');
}
}).complete(function(data){
});
}