【问题标题】:json response from php to select2 not rendering从 php 到 select2 的 json 响应未呈现
【发布时间】:2015-08-24 08:37:57
【问题描述】:

我正在尝试使用 select2 从 PHP 后端使用 AJAX 提取数据。我无法像我想的那样弄清楚文档。我想我可能错过了一些理所当然的东西。
我是这样开始的:

HTML

<select id="select_proj" style="width:10em">
  <option value="" selected="selected">Search</option>
</select>

js

$('select').select2();
$("#select_proj").select2({
    ajax : {
        url : '../app/select_prj.php',
        dataType : 'json',
        delay : 250,
        data : function (term, page) {
            return {
                select_proj: term, // search term
                page: 10
            };
        },
        processResults: function (data, page) {
            return {
                results: data.items
            };
        },
        cache: true
    },
    escapeMarkup : function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength : 1,
});

在 PHP 中

json 对象是从 PHP 中返回的

echo json_encode($result_data);

数据看起来像

[{
    "PROJ_ID" : 10039,
    "0" : 10039
},{
    "PROJ_ID" : 10042,
    "0":10042
}] 

但是,除了一条消息“未找到结果”之外,选择框中什么也没有发生。
我错过了什么?

【问题讨论】:

  • “未找到结果”在哪里?
  • 在用户输入条目下方的选择组件内

标签: javascript php jquery json jquery-select2


【解决方案1】:

您的回复必须如下所示:

[
    { id: 0, text: 'enhancement' },
    { id: 1, text: 'bug' }, 
    { id: 2, text: 'duplicate' },
    { id: 3, text: 'invalid' }, 
    { id: 4, text: 'wontfix' }
]
  • “id”将是选项值
  • “文本”将是选项标签

并且您必须从“data.items”中删除“.items”,因为您的回复中没有关键“items”。

【讨论】:

  • 非常感谢。在文档中找不到这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 2015-09-20
  • 2014-09-06
  • 2021-05-11
  • 2020-11-29
相关资源
最近更新 更多