javascript - 使用 PHP 的 Select2 optgroup 格式
问题描述
我有一个获取动态数据并将它们放在 select2 中的 ajax 调用,如下所示:
$.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++;
}
推荐阅读
- javascript - 在第二个连字符之前拆分和抓取文本
- python - 在 Colab 中安装 MeshPy
- python - 无法加载自定义数据集
- react-native - Android 依赖 'com.airbnb.android:lottie' 有不同版本的编译(2.5.5)和运行时(2.5.6)类路径
- autocomplete - 如何使用 Map 函数解析这个 javascript 数组?
- javascript - 如何可视化网站的 js 依赖项
- android - 如何在多个图像视图中设置多个图像
- java - My app keeps on crashing and I am not able to see what the problem is
- mysql - 内连接显示输出中的重复行。它多次显示数据
- ionic-framework - 使用 Ionic 的自动检测应用程序