prosource

jQuery의 select2 ajax 호출에 매개 변수 전달

probook 2023. 8. 26. 11:57
반응형

jQuery의 select2 ajax 호출에 매개 변수 전달

select2 내에서 추가 매개 변수를 Ajax 호출에 전달하려고 합니다.

  $(".auto-sug").select2({
    width:'element',
    minimumInputLength:2,
    ajax: {
        url: "/action/get-custom.php",
        data: function (term, page) {
          return {
              q: term, // search term
              page_limit: 10
          };
        },
        results: function (data, page) {
            return {results: data.stuff};
        }
    }
  });

아약스 호출에 다른 매개 변수를 전달하고 싶습니다.요소 자체의 아이디

<input type="text" class="auto-sug" name="custom" id="3383" />

하지만 실제로 요소의 id(3383)나 페이지의 다른 값에 액세스하는 방법을 알 수 없습니다.

요청할 때마다 실행되도록 루트 Ajax 대신 데이터 함수 내부에 추가 매개 변수를 전달해야 합니다.

ajax: {
    url: "/action/get-custom.php",
    data: function (term, page) {
      return {
          q: term, // search term
          anotherParm: whatEverValue, //Get your value from other elements using Query, for example.
          page_limit: 10
      };

그런 다음 현재 선택2에 대한 ID를 얻기 위해 대체할 수 있습니다.whateverValue와 함께$(this).data(key)

그러면 엔드포인트의 URL이 생성됩니다.

/action/get-custom.php?q=term&anotherParm=whatEverValue&page_limit=10

클래스가 있는 요소가 여러 개 있다고 가정합니다.auto-sug당신은 다음과 같은 것을 시도할 수 있습니다:

$(".auto-sug").each(function() {
    var thisId = this.id;
    $(this).select2({
        ...
        ajax: {
            ...
            id: thisId,
        },
    });
});

여기에 새 매개 변수를 추가할 수 있습니다.

 data: function (params) {
        ultimaConsulta = params.term;
        localidad = $("#idOcultoLocalidad").val(); //this is the anotherParm
        return {
            criterio: params.term, // search term
            criterio2: localidad,
        };
    },

언급URL : https://stackoverflow.com/questions/13637841/passing-parameters-to-jquerys-select2-ajax-call

반응형