【问题标题】:Select2 not working, always displaying "No results found"Select2 不工作,总是显示“未找到结果”
【发布时间】:2017-11-12 01:15:57
【问题描述】:

我已经尝试了这个站点上的所有内容,但没有任何效果,我只想从 servlet 生成的 JSON 中获取状态,然后使用 AJAX 在选择栏上显示数据。

但无论我在选择栏上键入什么内容,我都只会得到“未找到结果”。

这是填充下拉列表的函数:

注意:formatRepo 和 formatRepoSelection 已添加

$(document).ready(function() {
  $(".js-data-example-ajax").select2({
    ajax: {
      url: "/socialis/estadoController",
      dataType: 'json',
      delay: 250,
      data: function(params) {
        return {
          q: params.term, // search term
          page: params.page
        };
      },
      processResults: function(data, params) {
        // parse the results into the format expected by Select2
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;

        return {
          results: data.items,
          pagination: {
            more: (params.page * 30) < data.total_count
          }
        };
      },
      cache: true
    },
    escapeMarkup: function(markup) {
      return markup;
    }, // let our custom formatter work
    minimumInputLength: 1,
    templateResult: formatRepo, // omitted for brevity, see the source of this page
    templateSelection: formatRepoSelection // omitted for brevity, see the source of this page

  });
});

这是 Servlet doGet 方法:

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String estados = new Gson().toJson(localizacionDao.getEstados());

        response.getWriter().write(estados);

    }

我通过每次在选择栏上键入时打印“estados”来验证 JSON 是否正确生成。

提前致谢。

【问题讨论】:

    标签: jquery json ajax servlets jquery-select2


    【解决方案1】:

    固定:

    基本上我使用的 JSON 格式是错误的,适合我的 JSON 格式是:

    [{"id":7,"text":"Chiapas"},{"id":8,"text":"Chihuahua"}]
    

    另外,对 Select2 函数的细微改动:

    $(".js-data-example-ajax").select2({
            ajax: {
              url: "/socialis/estadoController",
              dataType: 'json',
              type: "GET",
              delay: 250,
              data: function (params) {
                return {
                  q: params.term, // search term
                  page: params.page
                };
              },
              processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;
    
                return {
                  results: data,
                  pagination: {
                    more: (params.page * 30) < data.total_count
                  }
                };
              },
              cache: true
            },
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 1
    
          });
    

    控制器也发生了变化:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
        String searchTerm = request.getParameter("q");
    
        String estados = getOptions(searchTerm);              
    
        response.getWriter().write(estados);
    
    }
    

    需要注意的是,结果的过滤是在服务器端完成的,基本上 Ajax 发送一个带有搜索词的请求,名为“q”,每次你在搜索栏中输入内容。

    因此,在每个请求中,“getOptions”函数都会像这样过滤结果:

    public String getOptions(String q){
        List<Estados> estados = localizacionDao.getEstados();
        List<Estados> estadosFiltered = new ArrayList<>();
        for (Estados Estado : estados) {
            if(Estado.getNombreEstado().contains(q)){
                estadosFiltered.add(Estado);
            }
        }
        String estadosString = new Gson().toJson(estadosFiltered);
        System.out.println(estados);
        estadosString = estadosString.replace("idEstado", "id");
        estadosString = estadosString.replace("nombreEstado", "text");
        return estadosString;
    }
    

    我希望这个答案会有所帮助。

    【讨论】:

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