Javascript Select2 Ajax 方法未选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14819865/
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-24 18:01:59  来源:igfitidea点击:

Select2 Ajax Method Not Selecting

javascriptjqueryajaxjquery-select2jquery-select2-3

提问by AlbertEngelB

Ok, I'm sure there's something simple set wrong here but I'm not 100% what it is.

好的,我确定这里有一些简单的设置错误,但我不是 100% 是什么。

So I am trying to use Select2AJAX method as a way of users to search a database and select a result. The call itself is coming back with results, however it will not allow me to select the answer from the list. It also doesn't seem to allow you to "select" it on hover or up/ down arrow. So without further ado, here is my code:

所以我试图使用Select2AJAX 方法作为用户搜索数据库和选择结果的一种方式。电话本身会返回结果,但它不允许我从列表中选择答案。它似乎也不允许您在悬停或向上/向下箭头时“选择”它。所以不用多说,这是我的代码:

index.html

索引.html

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="select2/select2.css" media="screen" />
        <script src="select2/select2.js"></script>
        <script src="select.js"></script>
    </head>
    <body>
        <input type="text" style="width: 500px" class="select2">
    </body>
</html>

select.js

选择.js

jQuery(function() {

  var formatSelection = function(bond) {
    console.log(bond)
    return bond.name
  }

  var formatResult = function(bond) {
    return '<div class="select2-user-result">' + bond.name + '</div>'
  }

  var initSelection = function(elem, cb) {
    console.log(elem)
    return elem
  }

    $('.select2').select2({
      placeholder: "Policy Name",
      minimumInputLength: 3,
      multiple: false,
      quietMillis: 100,
      ajax: {
        url: "http://localhost:3000/search",
        dataType: 'json',
        type: 'POST',
        data: function(term, page) {
          return {
            search: term,
            page: page || 1
          }
        },
        results: function(bond, page) {
          return {results: bond.results, more: (bond.results && bond.results.length == 10 ? true: false)}
        }
      },
      formatResult: formatResult,
      formatSelection: formatSelection,
      initSelection: initSelection
    })
})

JSON Response

JSON 响应

{
  error: null,
  results: [
    {
      name: 'Some Name',
      _id: 'Some Id'
    },
    {
      name: 'Some Name',
      _id: 'Some Id'
    }
  ]
}

Everything seems to pull in correctly, however I am unable to actually select the answer and have it input into the box. Is there a problem somewhere in my code?

一切似乎都正确无误,但是我无法实际选择答案并将其输入框中。我的代码中某处有问题吗?

回答by AlbertEngelB

After looking at another answerit would seem I need to also pass id field with every call, otherwise it will disable the input.

查看另一个答案后,似乎我还需要在每次调用时传递 id 字段,否则它将禁用输入。

Sample code that fixed it:

修复它的示例代码:

$('.select2').select2({
  placeholder: "Policy Name",
  minimumInputLength: 3,
  multiple: false,
  quietMillis: 100,
  id: function(bond){ return bond._id; },
  ajax: {
    url: "http://localhost:3000/search",
    dataType: 'json',
    type: 'POST',
    data: function(term, page) {
      return {
        search: term,
        page: page || 1
      }
    },
    results: function(bond, page) {
      return {results: bond.results, more: (bond.results && bond.results.length == 10 ? true: false)}
    }
  },
  formatResult: formatResult,
  formatSelection: formatSelection,
  initSelection: initSelection
})

Edit

编辑

Since this keeps getting upvoted I'll elaborate a bit. The .select2() method expects a unique idfield on all results. Thankfully, there's a workaround. The idoption accepts a function like this:

由于这不断得到赞成,我将详细说明。.select2() 方法id要求所有结果都有一个唯一的字段。幸运的是,有一个解决方法。该id选项接受这样的函数:

function( <INDIVIDUAL_RESULT> ) {
  // Expects you to return a unique identifier.
  // Ideally this should be from the results of the $.ajax() call. 
}

Since my unique identifier was <RESULT>._id, I simply return <RESULT>._id;

由于我的唯一标识符是<RESULT>._id,我只是return <RESULT>._id;

回答by Andres Gonzalez

The thing is that the JSON data need a property called "id". There's no need for

问题是 JSON 数据需要一个名为“id”的属性。没有必要

id: function(bond){ return bond._id; }

id: function(bond){ return bond._id; }

If the data does not have an id for itself, you can add it with a function on processResultslike here.

如果数据本身没有 id,您可以使用processResults上的函数添加它, 如下所示。

        $(YOUR FIELD).select2({
            placeholder: "Start typing...",
            ajax: {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "YOUR API ENDPOINT",
                dataType: 'json',
                data: 
                    function (params) {
                        return JSON.stringify({ username: params.term });
                },
                processResults: function (data, page) {

                    var results = [];

                    $.each(JSON.parse(data.d), function (i, v) {
                        var o = {};
                        o.id = v.key;
                        o.name = v.displayName;
                        o.value = v.key;
                        results.push(o);
                    })

                    return {
                        results: results
                    };
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup;},
            minimumInputLength: 1,
            templateResult: function (people) {
                if (people.loading)
                    return people.text;

                var markup = '<option value="' + people.value + '">' + people.name + '</option>';

                return markup;
            },
            templateSelection: function (people) { return people.value || people.text }

        });    

回答by Anh Cao

Like Dropped.on.Capricasaid: Every result item needs an unique id.

就像Dropped.on.Caprica说的:每个结果项都需要一个唯一的 id。

So just assign every result idan unique number:

因此,只需为每个结果分配id一个唯一编号:

$('#searchDriver').select2({
    ajax: {
       dataType: 'json',
       delay: 250,
       cache: true,
       url: '/users/search',
       processResults: function (data, params) {
           //data is an array of results
           data.forEach(function (d, i) {
               //Just assign a unique number or your own unique id
               d.id = i; // or e.id = e.userId;
           })

           return {
               results: data
           };
       },
    },
    escapeMarkup: function (markup) { return markup; },
    minimumInputLength: 1,
    templateResult: formatRepo,
    templateSelection: formatRepoSelection
});

回答by Eugene

Also be careful with the case. I was using Idbut select2 expects id. Could save someone's time.

还要小心这种情况。我正在使用Id但 select2 期望id. 可以节省某人的时间。

回答by Ebrahim

I have many problem regarding the following error Option 'ajax' is not allowed for Select2

我有很多关于以下错误的问题 Select2 不允许选项“ajax”

In my case, appears for select when you are using select2 version 3.5, So you should upgrade to version 4.0 and you won't need hidden input attached to your select

在我的情况下,当您使用 select2 3.5 版时会出现 select,所以您应该升级到 4.0 版,并且您不需要隐藏输入附加到您的选择

回答by Justin Leveck

enter image description here

在此处输入图片说明

You can trigger selecting an option (in this case the first one) by opening the select2element programmatically and then triggering a returnkeypress.

您可以通过以select2编程方式打开元素然后触发return按键来触发选择一个选项(在本例中为第一个)。

var e = jQuery.Event('keydown');
e.which = 13;

$('.offer_checkout_page_link select').select2('open');
$('.offer_checkout_page_link .select2-selection').trigger(e);

This will "set" the option as if you clicked on it. You can modify this to select a specific option by triggering the appropriate number of downkeypresses before triggering the returnone.

这将“设置”该选项,就像您单击它一样。您可以通过down在触发之前触发适当数量的按键来修改它以选择特定选项return

It seems as though under-the-hood when you click (or in this case hit enter) to select an option, an option element is added to the select element. You will notice that when the page first loads select2select elements do not have any optionelement children. This is why other solutions suggest adding an option element using jQuery and then selecting it.

当您单击(或在本例中为 hit enter)选择一个选项时,似乎在幕后,一个选项元素被添加到选择元素中。您会注意到,当页面首次加载时,select2选择元素没有任何子option元素。这就是为什么其他解决方案建议使用 jQuery 添加一个选项元素然后选择它。