使用PHP选择2 optgroup格式

问题描述 投票:0回答:1

我有一个获取动态数据的ajax调用,并将它们放在select2中,如下所示:

$.ajax({
    type: 'get',
    url: '/api/?stuff='+c,
    dataType: "json",
    success: function (response) {
        // If select2 is already defined, we destroy it and rebuild it with the new data
        if(typeof $(".select2edit").data('select2') !== 'undefined') {
            $(".select2edit").select2('destroy').select2({ data: response, width: '100%', closeOnSelect: false });
        } else {
            $(".select2edit").select2({ data: response, width: '100%', closeOnSelect: false });
        }
    }
});

我使用PHP创建响应,然后在发送之前将其转换为JSON:

$old_emplacement = '';
$results = array();
$i = -1;

while($array_campaign = tep_db_fetch_array($campaign)){
    if ($array_campaign['name'] != $old_emplacement) {
        $i++;
        $results['results'][$i]['text'] = $array_campaign['name'];
        $old_emplacement = $array_campaign['name'];
        $c = 0;
    }
    $results['results'][$i]['children'][$c]['id'] = $array_campaign['id'];
    $results['results'][$i]['children'][$c]['text'] = $array_campaign['c_name'];
    $c++;
}

$results['pagination']["more"] = true; 

从而产生以下JSON格式:

{
  "results": [
    { 
      "text": "Name 1", 
      "children" : [
        {
            "id": 1,
            "text": "Text 1.1"
        },
        {
            "id": 2,
            "text": "Text 1.2"
        }
      ]
    },
    { 
      "text": "Name 2", 
      "children" : [
        {
            "id": 1,
            "text": "Text 2.1"
        },
        {
            "id": 2,
            "text": "Text 2.2"
        }
      ]
    }
  ],
  "paginate": {
    "more": true
  }
}

当select2初始化并加载时,我得到一个No results found.。我不明白为什么。这是正确的格式,就documentation说,other questions似乎证实。问题可能来自哪里?

值得注意的是,我的select2位于一个模态内部的形式中,这就是它的html:

<select name="xx[]" id="edit-xx" name='xx' class="form-control select2edit" multiple>
</select> 
javascript php jquery-select2
1个回答
1
投票

问题在于我的PHP代码生成的格式。我在这里发布结果给任何试图使用PHP生成select2 optgroup格式并且我自己参考的人:

$old_emplacement = '';

$results = array();
$i = -1;

while($array_campaign = tep_db_fetch_array($campaign)){
    if ($array_campaign['name'] != $old_emplacement) {
        $i++;
        $results[$i]['text'] = $array_campaign['name'];
        $old_emplacement = $array_campaign['name'];
        $c = 0;
    }
    $results[$i]['children'][$c]['id'] = $array_campaign['id'];
    $results[$i]['children'][$c]['text'] = $array_campaign['c_name'];
    if(in_array($array_campaign['id'], $campaigns_array)) {
        $results[$i]['children'][$c]['selected'] = true;
    }
    $c++;
}
© www.soinside.com 2019 - 2024. All rights reserved.