【问题标题】:select2 ajax won't display json data returnedselect2 ajax 不会显示返回的 json 数据
【发布时间】:2013-02-16 03:04:46
【问题描述】:

这是从我的coldfusion页面返回的json字符串的样子:[{"client":"Asante","id":12},{"client":"City of Lancaster","id":14},{"client":"Massey Energy","id":35},{"client":"Northeast Utilities","id":68},{"client":"Washtenaw","id":50}]。 Firebug 声称一切正常,但 select2 插件中没有显示任何数据。

有谁知道可能是什么问题?它应该返回列名还是什么?

select2 调用:

$(".select").select2({
    allowClear: true,
    blurOnChange: true,
    openOnEnter: false,
    ajax: {
        url: "/surveymanagement/admin/client.cfc",
        dataType: 'json',
        data: function (term, page) {
            return {
                method: "GetClientsByName",
                name: term
            };
        },
        results: function (data, page) {
            return { results: data };
        }
    }
});

【问题讨论】:

  • 您的数据格式必须为[{"text":"Asante","id":12}, ...],否则您需要通过{results: data, text: 'client'}

标签: jquery json jquery-select2


【解决方案1】:

您的数据格式必须为[{"text":"Asante","id":12}, ...],否则您需要传递{results: data, text: 'client'}

【讨论】:

    【解决方案2】:

    如果您的 json 字符串需要使用 "text": "something" 以外的其他内容,则需要添加以下内容:使用 formatResults 来获取要显示的数据。这是固定版本:

    $(".select").select2({
        allowClear: true,
        blurOnChange: true,
        openOnEnter: false,
        ajax: {
            url: "/surveymanagement/admin/client.cfc",
            dataType: 'json',
            data: function (term, page) {
                return {
                    method: "GetClientsByName",
                    name: term
                };
            },
            results: function (data, page) {
                return { results: data };
            }
        },
        formatResult: function (data) {
            return "<div class='select2-user-result'>" + data.client + "</div>";
        },
        formatSelection: function (data) {
            return data.client;
        }
    });
    

    否则 Arun 是对的,您只需要使用格式 [{"id":1,"text":"client"}]

    【讨论】:

      【解决方案3】:

      是的,它太旧了 :) 但我今天需要它并像这样解决了它(使用 Symfony2):

      $opts = [];
      
      foreach($items as $item)
      
          $opts['results'][] = ['text' => $item->getXyz(), 'id' => $sk->getId()];
      
      return new JsonResponse($opts);
      

      关键的“结果”很重要

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        • 2012-04-20
        • 2015-09-17
        相关资源
        最近更新 更多