我想在我制作的可搜索下拉列表中的选项前面添加一个图像。该列表填充了通过 PHP 和 AJAX 检索的 MySQL 数据库中的数据。我正在使用 Select2 插件来解决这个问题,并且我成功地使其能够处理数据库中的简单数据,但我不知道如何将图像(图像的链接存储在数据库中)添加到选项中。我读过这个article ,但我不知道如何将这些信息实现到我的代码中。
这是我到目前为止所做的:
HTML
<select id="js-hieroglyph-code-select" name="hieroglyph-code-input" data-width="100%">
<option value="" selected disabled>Select hieroglyph code</option>
</select>
JS/Jquery
$("#js-hieroglyph-code-select").select2({
ajax : {
url : "./includes/individual_retrieve_scripts/retrieve_hieroglyph_undefined.script.php",
type : "POST",
dataType : "json",
delay : 250,
data : function(params){
return {
hieroglyphCodeValue : params.term
};
},
processResults : function(response){
return {
results : response
};
},
cache : true
}
});
PHP
$data = array(["id" => "0", "text" => "Hieroglyph without code"]);
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array(
"id" => $row["undefined_hieroglyph_code"],
"text" => $row["undefined_hieroglyph_code"]
);
}
echo json_encode($data);
exit();
为了方便起见,我故意省略了 PHP 代码中的数据库查询部分,但我认为这对于这里的问题并不重要。
我考虑过在 PHP 中连接图像链接数据和文本数据,然后在 Javascript 中将其分离,但这只是一个想法,我不知道如何进一步使用分离的数据。像这样的事情:
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array(
"id" => $row["undefined_hieroglyph_code"],
"text" => $row["undefined_hieroglyph_code"]."/".$row["image_link"]
);
}
这个问题有解决办法吗?
最佳答案
我建议您看看 select2 templateResult 选项 here 您应该首先将图像的 URL 作为单独的键添加到结果中,然后在模板化 select2 的函数中使用它
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array(
"id" => $row["undefined_hieroglyph_code"],
"text" => $row["undefined_hieroglyph_code"],
"imageUrl" => $row["image_link"]
);}
关于php - jquery - 如何使用通过 AJAX 从 MySQL 和 PHP 检索的数据将图像添加到 Select2 下拉列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417593/