带有 ajax 的 jquery-select2 multi 的 JSON 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16598549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:26:35  来源:igfitidea点击:

JSON format for jquery-select2 multi with ajax

javascriptjquerytwitter-bootstrapjquery-select2jquery-chosen

提问by Johann Echavarria

I'm thinking in moving from Chosen to Select2 because Select2 has native methods for ajax. Ajax is critical because usualy you have to load a lot of data.

我正在考虑从 Chosen 转移到 Select2,因为 Select2 具有用于 ajax 的本机方法。Ajax 很关键,因为通常您必须加载大量数据。

I executed sucessfully the example with the JSON of api.rottentomatoes.com/api/

我使用 api.rottentomatoes.com/api/ 的 JSON 成功执行了示例

I did a JSON file to test the ajax, but it didn't works.

我做了一个 JSON 文件来测试 ajax,但是没有用。

I don't know how the JSON should be. It seems that there is no detailed documentation:

我不知道 JSON 应该如何。好像没有详细的文档:

https://github.com/ivaynberg/select2/issues/920

https://github.com/ivaynberg/select2/issues/920

I tried unsucessfully several JSON formats, so I tried to copy a JSON format similar to api.rottentomatoes but it doesn't works.

我尝试了几种 JSON 格式都没有成功,所以我尝试复制一个类似于 api.rottentomatoes 的 JSON 格式,但它不起作用。

I may be missing something stupid.

我可能错过了一些愚蠢的东西。

function MultiAjaxAutoComplete(element, url) {
    $(element).select2({
        placeholder: "Search for a movie",
        minimumInputLength: 1,
        multiple: true,
        ajax: {
            url: url,
            dataType: 'jsonp',
            data: function(term, page) {

                return {
                    q: term,
                    page_limit: 10,
                    apikey: "z4vbb4bjmgsb7dy33kvux3ea" //my own apikey
                };
            },
            results: function(data, page) {
                return {
                    results: data.movies
                };
            }
        },
        formatResult: formatResult,
        formatSelection: formatSelection,
        /*initSelection: function(element, callback) {
            var data = [];
            $(element.val().split(",")).each(function(i) {
                var item = this.split(':');
                data.push({
                    id: item[0],
                    title: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }*/
    });
};

function formatResult(node) {
    return '<div>' + node.id + '</div>';
};

function formatSelection(node) {
    return node.id;
};


/*MultiAjaxAutoComplete('#e6', 'http://api.rottentomatoes.com/api/public/v1.0/movies.json');*/

MultiAjaxAutoComplete('#e6', 'https://raw.github.com/katio/Quick-i18n/master/test.json');

$('#save').click(function() {
    alert($('#e6').val());
});

I did this jsfiddle:

我做了这个jsfiddle:

http://jsfiddle.net/Katio/H9RZm/4/

http://jsfiddle.net/Katio/H9RZm/4/

回答by igor.vaynberg

If you switched to JSON make sure you switch dataType to JSON from JSONP.

如果您切换到 JSON,请确保将 dataType 从 JSONP 切换到 JSON。

The format is specified here: http://ivaynberg.github.io/select2/#doc-query

格式在此处指定:http: //ivaynberg.github.io/select2/#doc-query

The JSON should look like this:

JSON 应如下所示:

{results: [choice1, choice2, ...], more: true/false }

Basically the only required attribute in the choice is the id. if the option contains other child options (such as in case of optgroup-like choices) then those are specified inside the childrenattribute.

基本上,选择中唯一需要的属性是id. 如果该选项包含其他子选项(例如在类似 optgroup 的选择的情况下),则在children属性中指定这些选项。

The default choice and selection renderer expect a textattribute in every choice - that's what is used to render the choice.

默认选择和选择渲染器期望text在每个选择中都有一个属性 - 这就是用于渲染选择的属性。

so a complete example of a US state using default renderer might look like this:

因此,使用默认渲染器的美国州的完整示例可能如下所示:

{
    "results": [
        {
            "id": "CA",
            "text": "California"
        },
        {
            "id": "CO",
            "text": "Colarado"
        }
    ],
    "more": false
}

Hope this gets you started.

希望这能让你开始。

回答by Nicola Beghin

Official documentation for required JSON format: ref. https://select2.org/data-sources/formats

所需 JSON 格式的官方文档:参考。https://select2.org/data-sources/formats

{
  "results": [
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
  ],
  "pagination": {
    "more": true
  }
}