【问题标题】:jquery - JSON object, formatted for <optgroup >, returned by AJAX from PHP and MySQL doesn't work in Select2jquery - JSON 对象,格式为 <optgroup>,由 PHP 和 MySQL 的 AJAX 返回,在 Select2 中不起作用
【发布时间】:2020-04-14 06:39:42
【问题描述】:

我花了一整天的时间尝试制作一个 PHP 脚本,将 MySQL 查询结果转换为 Select2 中 &lt;optgroup&gt; 的 JSON 对象,当我终于找到解决方案时,它不起作用(Select2 下拉菜单中没有任何内容)。我只是整个编程的初学者,我真的不知道如何解决这个问题。 Stack 上的其他答案并没有真正帮助我。这是我到目前为止得到的:

PHP

$gardinersClasses = array(
    "A. Man and his Occupations",
    "B. Woman and her Occupations",
    "C. Anthropomorphic Deities",
    "D. Parts of the Human Body",
    ...etc.
);

$results = array();
$data = array();
$rowNumber = mysqli_num_rows($fetchData);

if ($rowNumber > 0) {
    while ($row = mysqli_fetch_array($fetchData, MYSQLI_ASSOC)) {
        $results[] = array(
            "id" => $row["id"],
            "text" => $row["hieroglyph_hieroglyphica_code"],
            "class" => $row["gardiners_class_id"]
        );
    }
    usort($results, function($a, $b) {
        $retVal = $a["class"] <=> $b["class"];
        if ($retVal == 0) {
            $retVal = strnatcmp($a["text"], $b["text"]);
        }
        return $retVal;
    });

    foreach($results as $result) {
        $gardinersClassNumber = $result["class"]-1;
        $gardinersClass = $gardinersClasses[$gardinersClassNumber];
        if (empty($data)) {
            $data[$gardinersClassNumber] = array(
                "text" => $gardinersClass,
                "children" => array(array(
                        "id" => $result["id"],
                        "text" => $result["text"]
                    )
                )
            );
        } else {
            $counter = 0;
            foreach ($data as $subdata) {
                if (in_array($gardinersClass, $subdata)) {
                    $counter++;
                }
            }
            if ($counter < 1) {
                $data[$gardinersClassNumber] = array(
                    "text" => $gardinersClass,
                    "children" => array(array(
                            "id" => $result["id"],
                            "text" => $result["text"]
                        )
                    )
                );
            } else {
                $data[$gardinersClassNumber]["children"][] = array(
                    "id" => $result["id"],
                    "text" => $result["text"]
                );
            }
        }
    }
}

echo json_encode($data);
exit();

JSON(由 AJAX 接收)

{
"0": {
    "text": "A. Man and his Occupations",
    "children": [{
        "id": 1080,
        "text": "A1A"
    }, {
        "id": 1077,
        "text": "Hgn4"
    }, {
        "id": 1078,
        "text": "Hgn5"
    }]
},
"10": {
    "text": "L. Invertebrata and Lesser Animals",
    "children": [{
        "id": 1076,
        "text": "877"
    }, {
        "id": 1079,
        "text": "Hgn6"
    }]
},
"11": {
    "text": "M. Trees and Plants",
    "children": [{
        "id": 1074,
        "text": "9"
    }]
},
"13": {
    "text": "NL. Nomes of Lower Egypt",
    "children": [{
        "id": 1081,
        "text": "A1B"
    }]
},
"28": {
    "text": "Hgn. Hieroglyphicon Unclassified",
    "children": [{
        "id": 1072,
        "text": "Hgn1"
    }, {
        "id": 1073,
        "text": "Hgn2"
    }, {
        "id": 1075,
        "text": "Hgn3"
    }]
}
}

JQuery & Select2

function hieroglyphSelectMimic(selectionField, phpScript, picture = false) {
function formatItem(item) {
    if (!item.id) {
        return item.text;
    }
    if (item.id == "x") {
        return $("<span class='select-option-hieroglyph grey-text text-14'>" + item.text + "</span>");
    } else {
        if (!picture) {
            return item.text;
        } else {
            return $("<span class='select-option-hieroglyph'><img class='hieroglyph-intext' src='./images/hieroglyphs/" + item.text + ".svg' onerror='this.src=\"./images/hieroglyphs/unknown.svg\"'> " + item.text + "</span>");
        }

    }
}
selectionField.select2({
    ajax : {
        url : phpScript,
        type : "POST",
        dataType : "json",
        delay : 350,
        data : function(params){
            return {
                term : params.term
            };
        },
        processResults : function(response) {
            return {
                results : response
            };
        },
        cache : true
    },
    templateResult : formatItem,
    language: {
        noResults: function (params) {
            return "Entered code doesn't exists.";
        }
    }
});
}

HTML

<select id="js-hieroglyph-hieroglyphica-code-select" name="hieroglyph-hieroglyphica-code-select" class="dropdown-style" data-width="100%">
    <option value="" disabled selected>Select hieroglyph code</option>
</select>
<script>
    var hieroglyphCodeSelect = $("#js-hieroglyph-hieroglyphica-code-select");
    phpScript = "./includes/individual_retrieve_scripts/retrieve_hieroglyphs_undefined.script.php";
    hieroglyphSelectMimic(hieroglyphCodeSelect, phpScript);
</script>

任何帮助将不胜感激。

【问题讨论】:

  • 那么您究竟在哪里尝试将返回的 Json 数据添加到代码中的 select 元素中?我没有看到 select 元素。
  • 对不起,我没有把 HTML 部分的代码放在这里。我会立即更新答案。
  • 我明白了,您正在尝试使用select2。我对此并不熟悉,但如果您是编程新手,最好使用一些普通的 JavaScript 来操作数据并创建一个 select 元素并使用您从 ajax 函数返回的数据填充它.
  • 看看this answer,看看是否有帮助。
  • 感谢您的回答。我知道那些基本的东西,但是对于我的项目,我特别需要 Select2 可以提供的东西。这就是我花了这么多时间试图弄清楚的原因。

标签: php jquery mysql json jquery-select2


【解决方案1】:

我无意中找到了解决方案。问题出在$data 数组中的key 中,该数组是用$gardinersClassNumber 故意创建的。它应该是自动生成的。

这是正确的解决方案:

foreach($results as $result) {
    $gardinersClassNumber = $result["class"]-1;
    $gardinersClass = $gardinersClasses[$gardinersClassNumber];
    if (empty($data)) {
        $data[] = array(
            "text" => $gardinersClass,
            "children" => array(array(
                    "id" => $result["id"],
                    "text" => $result["text"]
                )
            )
        );
    } else {
        $counter = 0;
        foreach ($data as $subdata) {
            if (in_array($gardinersClass, $subdata)) {
                $counter++;
            }
        }
        if ($counter < 1) {
            $data[] = array(
                "text" => $gardinersClass,
                "children" => array(array(
                        "id" => $result["id"],
                        "text" => $result["text"]
                    )
                )
            );
        } else {
            $currentKey = key($data);
            $data[$currentKey]["children"][] = array(
                "id" => $result["id"],
                "text" => $result["text"]
            );
        }
    }
}

如您所见,当在数组中找到匹配项时,我使用key() 函数检索当前键,然后我使用它在该位置插入数据。

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    相关资源
    最近更新 更多