select2 ajax:定义formatResult,formatSelection和initSelection角色和行为

Séb*_*ien 2 ajax jquery json jquery-select2

我在我的网站上实现了一个基本的select2 ajax元素:

$(function(){
    $('#appbundle_marketplace_product_ingredient_barcode').select2({
        minimumInputLength: 10,
        multiple: false,
        allowClear: true,
        quietMillis: 50,
        placeholder: 'Commencez à taper le code barre ici',
        ajax: {
            data: function (term) {
                return {
                    q: term // search term
                };
            },
            url: function(term) {
                url="http://fr.openfoodfacts.org/api/v0/produit/" + term +".json";
                return url;
            },
            dataType: 'json',
            results: function(data) {
                if (data.status!=1) {return;}
                if (data.product.complete!=1) {return;}
                return {results: [{
                    text: data.code + " - " + data.product.product_name,
                    slug: data.code,
                    id: data.code
                }]};
            },
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我期待在模板方法formatResult,formatSelection和InitSelection的帮助下更好地显示.我已经阅读了网上的文档(不完全理解)和示例.

虽然我可以理解每种方法应该做什么,但我无法让它们正常工作.

至于formatResult,formatSelection和InitSelection:

  • 什么是/应该是它们的属性的格式(数组/对象/哪些键?)?
  • 什么是/应该是响应的格式?
  • 他们如何被选择2调用,他们的反应如何处理?

任何帮助,以了解这种行为将不胜感激!

Abh*_*nde 8

你们这些人使用Select2 4.x,把头撞在桌子上,问自己你做错了什么:

formatResult和formatSelection已重命名.

https://select2.github.io/announcements-4.0.html

重命名模板选项Select2以前提供了多个选项,用于使用formatSelection和formatResult选项格式化结果列表和所选选项,通常称为"格式化程序".由于"格式化程序"也用于本地化等内容,它们也已更改,因此它们已重命名为templateSelection和templateResult,并且它们的签名也已更改.

从以前版本的Select2迁移时,您应该参考有关模板的更新文档.