php - jquery - 如何使用通过 AJAX 从 MySQL 和 PHP 检索的数据将图像添加到 Select2 下拉列表中?

标签 php jquery mysql drop-down-menu jquery-select2

我想在我制作的可搜索下拉列表中的选项前面添加一个图像。该列表填充了通过 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/

相关文章:

jquery - 在 jQuery UI AJAX 加载的选项卡上传递变量

javascript - 使用 AJAX 更改 PHP db_query 参数

python - 使用带有 mysql unix 时间戳的 sqlalchemy 定义表

php - 如何以编程方式使用 PHP Lib 在 Google Console Cloud 平台中创建项目?

php - 在线游戏,或比 ajax 更快的发送/接收数据的东西

PHP SELECT distinct 不回显变量?

javascript - 如何在使用 PHP 和 JS 的自动完成表单中不允许不在数据库中的值

jquery - 如何通过Ajax将变量从grail的 Controller 传递到gsp文件?

mysql - 需要多少个连接到枢轴才能获得不同的标签?

php - CodeIgniter 随机 PHP fatal error : Call to a member function . .. 在... mysqli_driver.php 中的非对象上