You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让jQuery实时搜索组件传递product_id并在前端弹窗显示

修改jQuery Typeahead脚本以同时传递product_id并弹窗显示

我来帮你解决这个问题,要实现同时传递product_id并在弹窗显示,需要调整PHP返回的数据结构和jQuery Typeahead的配置,分三步来做:

第一步:修改PHP代码,返回包含ID和名称的对象数组

原来的PHP只返回了产品名称的纯数组,现在要改成返回包含product_id和product_name的对象数组,这样前端才能拿到关联的ID信息。另外,我还帮你修复了SQL注入风险,改用预处理语句来查询:

<?php
$key = $_GET['key'];
$array = array();
$con = mysqli_connect("localhost","root","","products");

// 使用预处理语句防止SQL注入
$query = mysqli_prepare($con, "select product_id, product_name from products where product_name LIKE ?");
$like_key = "%{$key}%";
mysqli_stmt_bind_param($query, "s", $like_key);
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);

while($row = mysqli_fetch_assoc($result)) {
    $array[] = array(
        'id' => $row['product_id'],
        'name' => $row['product_name']
    );
}

echo json_encode($array);
mysqli_close($con);
?>

第二步:调整jQuery Typeahead配置,处理对象数据并获取ID

原来的JS只处理了纯文本的返回值,现在需要配置displayKey指定显示的字段,然后监听typeahead:selected事件(这个事件比change更可靠,只有选中下拉选项时才触发)来获取选中项的ID:

<script>
$(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'products',
        remote: 'search.php?key=%QUERY',
        limit : 10,
        displayKey: 'name' // 指定下拉框显示产品名称
    });

    // 监听选中下拉项的事件
    $('.typeahead').on('typeahead:selected', function(event, selectedItem) {
        // selectedItem是从PHP返回的对象,包含id和name属性
        alert('选中的产品ID:' + selectedItem.id + '\n产品名称:' + selectedItem.name);
        
        // 如果需要把ID存储起来(比如提交表单用),可以添加隐藏输入框并赋值:
        // $('<input>').attr({type: 'hidden', name: 'product_id'}).val(selectedItem.id).appendTo('form');
    });
});
</script>

第三步:HTML部分无需修改

你的现有HTML代码保持不变即可,不需要额外调整:

<div class="bs-example">
    <input type="text" name="typeahead" class="typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Type your Query">
</div>

测试效果

当你输入关键词后,下拉框会正常显示产品名称,选中「First Product」时,弹窗就会显示对应的ID(比如1)和产品名称了。

内容的提问来源于stack exchange,提问作者Gian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:42:24