program story

Select2 Ajax 방법이 선택되지 않음

inputbox 2020. 10. 26. 07:57
반응형

Select2 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'
    }
  ]
}

모든 것이 올바르게 들어가는 것처럼 보이지만 실제로 답을 선택하여 상자에 입력 할 수는 없습니다. 내 코드 어딘가에 문제가 있습니까?


다른 답변을 살펴본 후에 는 모든 호출에서 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;


문제는 JSON 데이터에 "id"라는 속성이 필요하다는 것입니다. 필요가 없습니다

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

데이터에 자체 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 }

        });    

케이스도 조심하세요. 나는 사용하고 Id있었지만 select2는 id. 누군가의 시간을 절약 할 수 있습니다.


Dropped.on.Caprica가 말한 것처럼 모든 결과 항목에는 고유 한 ID가 필요합니다.

So just assign every result id an unique number:

$('#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

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


enter image description here

You can trigger selecting an option (in this case the first one) by opening the select2 element programmatically and then triggering a return keypress.

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.

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 select2 select elements do not have any option element children. This is why other solutions suggest adding an option element using jQuery and then selecting it.

참고URL : https://stackoverflow.com/questions/14819865/select2-ajax-method-not-selecting

반응형