javascript make select 2 use url set by outside source

懵懂的女人 提交于 2019-12-25 00:14:32

问题


I'm using select2 to pick out games from a database, however, the file I wish it to search from will change depending on what's selected from a dropdown.

How do I get it so select2 always uses the most up to date "picker_url"?

So if I select a certain option from a select box on a page, it changes the "picker_url" (an ajax file to do the search). The problem is, select2 only seems to use the original value.

Here's my current code:

    var picker_url = "test1.php";
    $(document).on('change', ".category_select", function(e)
    {
        var id = $(this).val();
        if (id == 16)
        {
            picker_url = "test2.php";
        }
    });

  $(".game_picker").select2({
    selectOnClose: true,
    width: '100%',
    ajax: {
    url: picker_url,
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term // search term
      };
    },
    processResults: function (data) {
      return {
        results: $.map(data, function(obj) {
          return { id: obj.id, text: obj.text };
        })
      };
    },
    cache: true,
  },
  minimumInputLength: 2
  });

回答1:


Found the answer here: https://github.com/select2/select2/issues/1679#issuecomment-280080742

var someCondition
ajax: {
  url: function() {
    if (someCondition) {
      return '/api/1/someFile.json'
    } else {
      return '/api/1/someOtherFile.json'
    }
  }
}



回答2:


I suggest to use dynamic-urls, like the code below:

$('#mySelect2').select2({
  ajax: {
    url: function (params) {
      return '/some/url/' + params.term;
    }
  }
});

Inside url function you can test other variables than params, like in the following snippet:

$('#category').select2({
  placeholder: "Select category...",
  width: '100%',
});

$('#category').on('select2:select', function(e) {
  var data = e.params.data;
  console.log("category", data);
  categ = e.params.data.id;
});
var categ = "1";

$('#project').select2({
  placeholder: "Select item...",
  width: '100%',
  ajax: {
    type: "GET",
    url: function(params) {
      console.log("ajax func", params, categ);
      var url = 'https://jsonplaceholder.typicode.com/comments?postId=' + categ
      return url;
    },
    cache: true,
    processResults: function(data) {
      return {
        results: $.map(data, function(obj) {
          return {
            id: obj.id,
            text: obj.name
          };
        })
      };
    },
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<div class="group">
  <select id="category">
    <option value="1">cat 1</option>
    <option value="2">cat 2</option>
  </select>
</div>
<br>
<div class="group">
  <select id="project">
    <option value=""></option>
  </select>
</div>



回答3:


I would save off your default options and then recreate the select2 whenever you need to by extending your new URL into the default options:

var defaultOptions = {
  selectOnClose: true,
  width: '100%',
  ajax: {
  url: "test1.php",
  dataType: 'json',
  delay: 250,
  data: function (params) {
    return {
      q: params.term // search term
    };
  },
  processResults: function (data) {
    return {
      results: $.map(data, function(obj) {
        return { id: obj.id, text: obj.text };
      })
    };
  },
  cache: true,
  minimumInputLength: 2
};

//Use default to create first time
$(".game_picker").select2(defaultOptions);

//On change, recreate
$(document).on('change', ".category_select", function(e)
{
    var options = defaultOptions;
    if ($(this).val() == 16)
    {
        //Create a new options object with the url updated
        options = $.extend({}, defaultOptions, { url: 'test2.php' });
    }
    
    //Create a select2 with the desired options
    $(".game_picker").select2(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


来源:https://stackoverflow.com/questions/48009382/javascript-make-select-2-use-url-set-by-outside-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!