select2来自post的createSearchChoice id

我使用select2作为标记输入,但在处理新标记的创建并将新标记id重新放回select2时我感到困惑

这个问题与Select2.js密切相关:为什么id与删除时更改的文本相同?

你可以从他的jsfiddle http://jsfiddle.net/7e8Pa/看到,当在createSearchChoice中找不到文本时,会创建新选项,id:-1,text:term,然后在on change事件中,更改id为5

我需要能够向服务器提交$.post ,然后获取id而不是使用静态5

问题是,如果我在createsearchoption中提交post,那么在标签tabe中找不到的每个击键都会创建一个新标签,并且在更改事件中尝试发布,我假设更改事件在ajax返回之前结束

 .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); }); }; 

我最终做的是使用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连接创建的

我发送一个post到我的服务器来创建该标签,通过从id中对新标签进行子网格排序(对于正则表达式更好,但我离题了),并且该post返回一个标签ID,然后我可以在单独的post中使用标记该项目

 .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

 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){ }); }