小编典典

Select2 Ajax方法未选择

ajax

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

因此,我尝试使用Select2
AJAX方法作为用户搜索数据库并选择结果的方式。通话本身返回了结果,但是不允许我从列表中选择答案。它似乎也不允许您在悬停或上/下箭头上“选择”它。因此,事不宜迟,这是我的代码:

index.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

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回应

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

一切似乎都能正确输入,但是我无法真正选择答案并将其输入框中。我的代码中是否存在问题?


阅读 325

收藏
2020-07-26

共1个答案

小编典典

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

修复它的示例代码:

$('.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
})

编辑

既然这总是被推崇,我会详细说明。.select2()方法期望id所有结果上都有唯一的字段。幸运的是,有一种解决方法。该id选项接受如下功能:

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

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

2020-07-26