Jquery Select2 4 - Ajax"未找到结果"使用自定义数据时

时间:2017-03-02 20:01:38

标签: javascript jquery ajax jquery-select2

我无法让Ajax示例在github example on the documentation page之外工作。

这是我尝试的内容:

https://jsfiddle.net/vhrpzcuv/8/

<select name="test" class="select2picker" style="width: 100%">
 <option value="test">test</option>
</select>

    $('.select2picker').select2({
    ajax: {
        url: "", //For testing don't do this.  
        dataType: 'json',
        data: function(params) {
            return {
                filter: params.term // search term
            };
        },
        processResults: function(data) {
            data = [{
                id: 0,
                text: 'enhancement'
            }];
            console.log(data);
            return data;
        }
    }
});

2 个答案:

答案 0 :(得分:1)

返回的数据需要用对象$('.select2picker').select2({ ajax: { url: "", //For testing don't do this. dataType: 'json', data: function(params) { return { filter: params.term // search term }; }, processResults: function(data) { data = [{ id: 0, text: 'enhancement' }]; console.log(data); return {results: data}; } } }); 包装。

https://jsfiddle.net/vhrpzcuv/9/

<html>
  <head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        $('#calculate').click(function(){
          var dropdown = $('#dropdown').val();
          var age      = $('#age').val();
          var output;
          if(dropdown == 'A'){
            output = age/20;
          }
          if(dropdown == 'B'){
            output = age/10;
          }
          if(dropdown == 'C'){
            output = age/5;
          }
          $('#outputlabel').text(output);
        });   
      });
    </script>
    </head>
          <body>
            <form name='ageform' action=''>
              <label>Age:</label><input type="text" id="age" size ='2'/>
              <label>Option:</label>
              <select id='dropdown'>
                <option value='A'>A</option>
                <option value='B'>B</option>
                <option value='C'>C</option>
              </select>
              <input type='button' id='calculate' value='calculate' />
              <label id='outputlabel'></label>
            </form>
          </body>
        </html>

答案 1 :(得分:0)

还需要在PHP(或其他)文件中设置标头。

对于PHP响应文件示例:

header('Content-Type: application/json');
echo json_encode($data);