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

实时搜索无法传递变量问题求助

问题修复:点击缩略图表单数据无法传递到movie.php

问题根源

  1. 事件冒泡导致表单提交中断:点击缩略图时,事件会冒泡到.result容器,触发原有JS逻辑清空结果容器,表单在提交完成前就被移除,数据无法传递到目标页面。
  2. 重复ID违反HTML规范:后端生成的多个表单及内部元素使用了重复ID(如btn_top、form-search),可能引发DOM解析和操作异常。
  3. SQL注入风险(附带修复):原SQL语句拼接方式错误,存在注入漏洞。

修复步骤

1. 修改前端JS代码,解决事件冲突

修改点击事件逻辑,判断点击目标是否为表单提交按钮,避免中断表单提交:

$(document).ready(function(){
    $('.search-box input[type="text"]').on("keyup input", function(){
        var inputVal = $(this).val();
        var resultDropdown = $(this).siblings(".result");
        if(inputVal.length){
            $.get("search_backend.php", {term: inputVal}).done(function(data){
                resultDropdown.html(data);
            });
        } else{
            resultDropdown.empty();
        }
    });
    
    // 仅在点击非表单提交按钮时执行输入框赋值
    $(document).on("click", ".result", function(e){
        if($(e.target).is('input[type="image"]')){
            return; // 放行表单提交逻辑
        }
        $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
        $(this).parent(".result").empty();
    });
});

2. 修复后端PHP代码,解决重复ID和SQL注入问题

移除重复ID,修正SQL语句写法,同时用htmlspecialchars防止XSS:

<?php include "../includes/db_connector.php";
 
if(isset($_REQUEST["term"])){
    
    $search_keyword = $_REQUEST["term"];
    // 正确使用预处理语句,避免SQL注入
    $sql = "SELECT title, img FROM jeffbox WHERE title LIKE ?";
    
    if($stmt = mysqli_prepare($db_connect, $sql)){
        mysqli_stmt_bind_param($stmt, "s", $param_term);
        // 匹配包含关键词的标题,前后都加%
        $param_term = '%' . $search_keyword . '%';
        
        if(mysqli_stmt_execute($stmt)){
            $result = mysqli_stmt_get_result($stmt);
            
            if(mysqli_num_rows($result) > 0){
                while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
                    $img = $row["img"];
                    $title = $row["title"];
                    ?>

<form method="post" action="movie.php">
    <input style="display: none;" type="text" name="title" value="<?php echo htmlspecialchars($title) ?>" />
    <input style="display: none;" type="text" name="latest" value="<?php echo htmlspecialchars($title) ?>" />
    <input type="image" name="image" src="images/<?php echo htmlspecialchars($img) ?>" alt="<?php echo htmlspecialchars($title) ?>">
</form>

<?php
} } else { echo "<p>No movies found</p>"; }
  }
 }
     
mysqli_stmt_close($stmt);
}
 
mysqli_close($db_connect);
?>

验证

修改完成后,点击缩略图表单会正常提交,movie.php中可通过$_POST['title']和$_POST['latest']获取到对应的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:15:42