【问题标题】:Jquery Select2 4 - Ajax "no results found" when using custom dataJquery Select2 4 - 使用自定义数据时Ajax“未找到结果”
【发布时间】:2017-03-02 20:01:38
【问题描述】:

我无法让 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;
        }
    }
});

【问题讨论】:

    标签: javascript jquery ajax jquery-select2


    【解决方案1】:

    返回的数据需要用对象{results:x}包装。

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

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

    【讨论】:

      【解决方案2】:

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

      PHP 响应文件示例:

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

      【讨论】:

        猜你喜欢
        • 2020-06-30
        • 2016-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        相关资源
        最近更新 更多