json从php回复到select2没有渲染

时间:2015-06-09 13:32:24

标签: javascript php jquery json jquery-select2

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

HTML

define CheckDir
$(foreach d,$1,$(call CheckIt,$d))
endef

JS

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

在PHP中

从PHP返回json对象

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

,数据看起来像

echo json_encode($result_data);

但是,除了消息&#34;未找到结果&#34; 之外,选择框中没有任何内容发生。 我错过了什么?

1 个答案:

答案 0 :(得分:1)

您的回复必须如下:

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

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