如何在HTML video的onplay事件中传递参数并写入数据库
解决HTML Video onplay事件传递参数的问题
你的核心问题是内联onplay事件调用函数时,没有传递当前video元素的上下文,导致$(this)无法获取对应视频的data-id。下面给出两种可行的解决方法:
方法一:修改内联事件,直接传递当前元素
修改后的HTML代码
<video class='player' onplay='myFunction(this)' data-id='$row[id]' oncontextmenu='return false;' width='300' height='180' controls controlsList='nodownload'> <source src='' type='video/mp4'> Your browser does not support the video tag. </video>
修改后的JavaScript代码
<script type='text/javascript'> function myFunction(videoElement){ $.ajax({ url: "check.php", method: "POST", data: { "videoId": $(videoElement).data("id") }, dataType:"Text", }); } </script>
方法二:使用jQuery事件绑定(推荐,分离结构与行为)
这种方式不需要在HTML中写内联事件,更符合前端开发规范:
修改后的HTML代码
<video class='player' data-id='$row[id]' oncontextmenu='return false;' width='300' height='180' controls controlsList='nodownload'> <source src='' type='video/mp4'> Your browser does not support the video tag. </video>
修改后的JavaScript代码
<script type='text/javascript'> $(document).ready(function(){ // 给所有class为player的video绑定play事件 $(".player").on("play", function(){ $.ajax({ url: "check.php", method: "POST", data: { "videoId": $(this).data("id") }, dataType:"Text", }); }); }); </script>
额外提醒:修复后端SQL注入风险
你当前的后端代码存在SQL注入漏洞,直接将用户传入的参数拼接到SQL语句中非常危险,建议使用预处理语句:
if(isset($_POST['videoId'])){ $videoId = $_POST['videoId']; // 假设$xx、$yy是已定义的合法变量 $stmt = mysqli_prepare($conn, "INSERT INTO video (videoId, xx, yy) VALUES (?, ?, ?)"); // 绑定参数,"sss"表示三个字符串类型的参数,根据实际类型调整 mysqli_stmt_bind_param($stmt, "sss", $videoId, $xx, $yy); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); }
内容的提问来源于stack exchange,提问作者Vikash Kumar
相关产品推荐
相关产品推荐

