我有一个Select2字段,它使用Ajax调用从远程源检索数据。我希望能够将列表粘贴到字段中以匹配结果。
我尝试了以下tokenizer
方法:
tokenizer: function (input, selection, callback) {
var parts,
part,
matched = [],
i,
j;
// replace whitespace with commas
input = input.replace(/[\s]+/g, ',');
// no comma no need to tokenize
if (input.indexOf(',') < 0) {
return;
}
parts = input.split(/[\,]+/g);
for (i = 0; i < parts.length; i += 1) {
part = parts[i];
part = part.trim();
// check for duplicates
if (matched.indexOf(part) > -1) {
continue;
}
// check if the part matches
for (j = 0; j < tagList.length; j += 1) {
if (part === tagList[j].id) {
matched.push(part);
callback({id: part, text: part});
break;
}
}
}
}
使用以下Ajax结果方法:
// yes, the results are being returned properly
results: function (data) {
var results = [],
len = data.length,
i;
for (i = 0; i < len; i += 1) {
if (data[i].extra && data[i].extra.isp_id) {
results.push({text: data[i].name, id: data[i].value, ispId: data[i].extra.isp_id, ispName: data[i].extra.isp_name});
} else {
results.push({text: data[i].name, id: data[i].value});
}
}
tagList = results; // obviously, tagList is declared in a scope accessible to the tokenizer method
return {results: results};
}
正如您所料,tagList
为空。我只是不确定如何针对结果数据运行tokenizer
方法。 (1)这可能吗?如果是这样,(2)我将如何做到这一点?
答案 0 :(得分:0)
如果您使用ajax,那么您应该在服务器端进行标记化。