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

JavaScript跨页面传值问题:如何传递页面输入值至另一页面

嘿,我来帮你搞定把输入的姓名传递到另一个页面的问题!你现在的表单用了POST提交,但纯静态HTML页面没法直接处理POST请求的内容,所以咱们可以用几种更适合静态场景的方法,或者调整实现方式,具体看你的需求:

方法1:改用GET方法,通过URL参数传递

这种方法最简单,适合不需要保密的内容(比如姓名),参数会显示在URL里,无需额外后端支持。

修改你的index.html表单:

<form action="display.html" method="get" id="name-form">
  <p>
    <label>Your full Name</label>:<br />
    <input type="text" name="fullName" required>
  </p>
  <p>
    <input type="submit" value="Submit">
  </p>
</form>

然后在display.html里添加JavaScript读取URL参数并展示:

<!DOCTYPE html>
<html>
<head>
  <title>Display Name</title>
</head>
<body>
  <h1>Your Name:</h1>
  <p id="display-name"></p>

  <script>
    // 解析URL中的查询参数
    const urlParams = new URLSearchParams(window.location.search);
    const fullName = urlParams.get('fullName');
    
    // 展示姓名
    if (fullName) {
      document.getElementById('display-name').textContent = fullName;
    } else {
      document.getElementById('display-name').textContent = 'No name provided';
    }
  </script>
</body>
</html>

方法2:使用localStorage存储数据(适合不想暴露在URL里的情况)

这种方法会把数据存在浏览器本地,提交时先存值再跳转,目标页面读取存储的内容即可。

修改index.html,添加表单提交监听:

<form action="#" id="name-form">
  <p>
    <label>Your full Name</label>:<br />
    <input type="text" name="fullName" required>
  </p>
  <p>
    <input type="submit" value="Submit">
  </p>
</form>

<script>
  document.getElementById('name-form').addEventListener('submit', function(e) {
    // 阻止默认表单提交行为
    e.preventDefault();
    // 获取输入的姓名
    const fullName = this.fullName.value;
    // 存储到localStorage
    localStorage.setItem('userFullName', fullName);
    // 跳转到display.html
    window.location.href = 'display.html';
  });
</script>

然后在display.html里读取存储的姓名:

<!DOCTYPE html>
<html>
<head>
  <title>Display Name</title>
</head>
<body>
  <h1>Your Name:</h1>
  <p id="display-name"></p>

  <script>
    // 从localStorage读取姓名
    const fullName = localStorage.getItem('userFullName');
    
    if (fullName) {
      document.getElementById('display-name').textContent = fullName;
      // 可选:读取后清除存储,避免下次打开页面还显示旧数据
      localStorage.removeItem('userFullName');
    } else {
      document.getElementById('display-name').textContent = 'No name found';
    }
  </script>
</body>
</html>

补充:如果一定要用POST方法(需要服务器支持)

如果你的页面部署在有后端服务的环境(比如Node.js、PHP等),可以保留POST提交,由后端处理后传递数据给目标页面。比如用PHP的话:

index.html保持原POST表单不变,然后创建display.php(注意后缀改为php):

<!DOCTYPE html>
<html>
<head>
  <title>Display Name</title>
</head>
<body>
  <h1>Your Name:</h1>
  <p><?php echo isset($_POST['fullName']) ? $_POST['fullName'] : 'No name provided'; ?></p>
</body>
</html>

但如果是纯静态HTML(无后端),POST方法没法直接获取提交的数据,所以前面两种方法更适合你。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:33:23