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

点击按钮跳转页面时PHP如何接收Javascript传递的变量

问题核心原因

你现有代码存在2个核心问题,无法实现预期效果:

  • 没有定义JS变量传递给PHP、以及跳转至recive.php的逻辑
  • 原代码使用jQuery语法但未引入对应依赖,点击事件绑定会直接报错

实现方案

这里提供两种常用实现方式,可按需选择:

方案1:POST提交跳转(贴合你现有PHP用$_POST取值的写法)

修改后的send.html代码

<html>
<body>
<button id="getbtn">Button</button>
<script>
// 用原生JS实现,无需引入额外依赖
document.getElementById('getbtn').addEventListener('click', function() {
  const string = "HelloWorld";
  // 动态创建POST表单实现跳转传参
  const form = document.createElement('form');
  form.action = 'recive.php';
  form.method = 'post';
  const input = document.createElement('input');
  input.type = 'hidden';
  input.name = 'string';
  input.value = string;
  form.appendChild(input);
  document.body.appendChild(form);
  form.submit();
});
</script>
</body>
</html>

recive.php优化代码(增加XSS安全防护)

<?php 
// 对输出内容做转义,避免恶意参数注入代码
echo htmlspecialchars($_POST["string"]);
?>

方案2:GET参数跳转(实现更简单)

修改后的send.html代码

<html>
<body>
<button id="getbtn">Button</button>
<script>
document.getElementById('getbtn').addEventListener('click', function() {
  const string = "HelloWorld";
  // 直接把参数拼在URL里跳转
  location.href = 'recive.php?string=' + encodeURIComponent(string);
});
</script>
</body>
</html>

修改后的recive.php代码

<?php 
echo htmlspecialchars($_GET["string"]);
?>

内容的提问来源于stack exchange,提问作者saya-ma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:54:01