简体   繁体   English

Select2 Ajax 方法未选择

[英]Select2 Ajax Method Not Selecting

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 Select2 AJAX method as a way of users to search a database and select a result.所以我试图使用Select2 AJAX 方法作为用户搜索数据库和选择结果的一种方式。 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:所以不用多说,这是我的代码:

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?我的代码中某处有问题吗?

After looking at another answer it 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 id field on all results. .select2() 方法要求所有结果都有一个唯一的id字段。 Thankfully, there's a workaround.幸运的是,有一个解决方法。 The id option accepts a function like this: 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;

The thing is that the JSON data need a property called "id".问题是 JSON 数据需要一个名为“id”的属性。 There's no need for没有必要

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 processResults like 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 }

        });    

Also be careful with the case.还要小心这种情况。 I was using Id but select2 expects id .我正在使用Id但 select2 需要id Could save someone's time.可以节省某人的时间。

Like Dropped.on.Caprica said: Every result item needs an unique id.就像Dropped.on.Caprica说的:每个结果项都需要一个唯一的 id。

So just assign every result id an 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
});

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 版,并且您不需要隐藏输入附加到您的选择

在此处输入图片说明

You can trigger selecting an option (in this case the first one) by opening the select2 element programmatically and then triggering a return keypress.您可以通过以编程方式打开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 down keypresses before triggering the return one.您可以通过在触发return之前触发适当数量的down按键来修改它以选择特定选项。

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.当您单击(或在本例中按enter )选择一个选项时,似乎在后台,一个 option 元素被添加到 select 元素中。 You will notice that when the page first loads select2 select elements do not have any option element children.您会注意到,当页面首次加载select2 select 元素没有任何option元素子元素。 This is why other solutions suggest adding an option element using jQuery and then selecting it.这就是为什么其他解决方案建议使用 jQuery 添加一个选项元素然后选择它。

I was binding select2 to a div , somehow that won't work with ajax as dataSource so that might help someone.我将select2绑定到div ,不知何故不能将ajax as dataSource因此可能会帮助某人。

<div id="testSelect2"> </div>

changed this to将此更改为

<select id="testSelect2"> </select>

And it started keeping the selected item.它开始保留所选项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM