簡體   English   中英

使用PHP的Select2 optgroup格式

[英]Select2 optgroup format using PHP

我有一個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
  }
}

No results found. 當select2初始化並加載時。 而且我不知道為什么。 文檔而言,這是正確的格式,並且其他問題似乎可以肯定。 任何想法可能出在哪里?

還需要注意的是,我的select2在模式內部的表單中,這是html:

<select name="xx[]" id="edit-xx" name='xx' class="form-control select2edit" multiple>
</select> 

問題出在我的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++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM