请参阅https://select2.github.io/examples.html,加载远程数据时会显示"搜索"文本.但是,我不知道为什么在我的案例中显示"未定义".
这是css文件.
<div class="col-sm-9">
<select class="js-data-example-ajax form-control" style="width:100%;">
<option value="select2/select2" selected="selected">select2/select2</option>
</select>
</div>
Run Code Online (Sandbox Code Playgroud)
和ajax调用的设置
$(".js-data-example-ajax").select2({
ajax: {
url: "/search/products",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
minimumInputLength: 1,
templateResult: formatProduct,
templateSelection: formatProductSelection
});
Run Code Online (Sandbox Code Playgroud)
结果:

对于上述问题有一个可能的解决方法。欢迎发表评论。
\n\n这是我之前写的代码,假设返回 JSON 是{"items":[{"id":1,"name":"Product1"},{"id":2,"name":"Product2"}]}
var formatProduct = function(data){\n return \'<div>\'+(data.name)+\'</div>\';\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我已将代码修改如下,并且“正在搜索...”文本再次显示:
\n\nvar formatProduct = function(data){\n return \'<div>\'+(data.name || data.text)+\'</div>\';\n}\nRun Code Online (Sandbox Code Playgroud)\n\nselect2.js第798行,远程加载数据时
\n\nthis.template(data, option);\nRun Code Online (Sandbox Code Playgroud)\n\nthis.template 指向 select2.js第 1058 行
\n\nResults.prototype.template = function (result, container) {\n var template = this.options.get(\'templateResult\');\n container.innerHTML = template(result);\n};\n// result is an object indicating whether the data is loading.\n// {disabled: true, loading: true, text: "Searching\xe2\x80\xa6"}\nRun Code Online (Sandbox Code Playgroud)\n\n这里的模板采用自定义参数“templateResult”并生成文本,因此自定义函数必须包含data.text,否则返回underfined。
| 归档时间: |
|
| 查看次数: |
9122 次 |
| 最近记录: |