Select2,其中包含从Django序列化的JSON数据

时间:2016-01-15 10:53:21

标签: javascript json django jquery-select2-4

我有Django序列化创建的JSON数据。 我用的例子是: Select2 Loading remote data但我仍然在没有找到任何内容的字段中获取信息。

enter image description here

select2应该改变什么才能使用Django生成的数据?

JSON数据:

[{
    "fields": {
        "sku": "8"
    },
    "model": "catalog.product",
    "pk": 8
},{
    "fields": {
        "sku": "9"
    },
    "model": "catalog.product",
    "pk": 9
}]

HTML:

<select class="js-data-example-ajax"><option value="3620194" selected="selected">select2/select2</option></select>

JavaScript的:

$('.js-data-example-ajax').select2({
  ajax: {
  url: "{% url 'catalog.views.product_sku_json' %}",
  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,
});

1 个答案:

答案 0 :(得分:2)

在github上通过kevin-brown回答:

您需要将结果重新映射为具有ID和文本键。

https://select2.github.io/announcements-4.0.html#changed-id

感谢Kevin!