【问题标题】:How to send HTML FORM data from one page to another using JavaScript如何使用 JavaScript 将 HTML FORM 数据从一个页面发送到另一个页面
【发布时间】:2016-08-12 08:05:00
【问题描述】:

我正在尝试使用 Javascript 将 HTML FORM 数据从一个页面发送到另一个页面。这是我的代码。假设我在 FORM.html 页面的“NAME”字段中输入任何文本。提交后,文本将显示在 DISPLAY.html 页面上。怎么做?请帮忙

FORM.html

<html>
<head>
<title>FORM</title>
</head>
<body>
<form method="GET" action="display.html">
NAME: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>

DISPLAY.html

<html>
<head>
<title>Display</title>
</head>
<body>
<p id="show">
Name: <!-- want to display the name here -->
</p>
</body>
</html>

【问题讨论】:

标签: javascript html forms


【解决方案1】:

如果您只想通过JavaScript 来完成,那么您可以使用window.localStorage 属性在本地存储name 对象。

Form.html

<html>
<head>
<title>FORM</title>
</head>
<body>
<form id="form" method="GET" action="display.html">
NAME: <input type="text" name="name" id="name">
<input type="button" value="Submit" onclick="submitForm()">
</form>
<script>
function submitForm(){
    if(typeof(localStorage) != "undefined"){
        localStorage.name = document.getElementById("name").value;
    }
    document.getElementById("form").submit();
}
</script>
</body>
</html>

Display.html

<html>
<head>
<title>Display</title>
</head>
<body onload="setData()">
<p id="show">
Name: <!-- want to display the name here -->
</p>
<script>
function setData(){
    if(typeof(localStorage) != "undefined"){
        document.getElementById("show").innerHTML = localStorage.name;
    }
}
</script>
</body>
</html>

【讨论】:

  • 感谢您的代码。它对我有用,但问题是当我按“Enter”按钮提交名称时,它显示的是以前的名称。新名称未显示。
【解决方案2】:

你在提交 FORM.html 表单时将名字保存在 url 中

当您使用在 onload 页面中运行的 javascript 函数加载 DISPLAY.html 表单时,您可以从 url 读取名称。

您必须为此替换 DISPLAY.html:

<html>
<head>
<title>Display</title>
</head>
<body onload="getName()">
<p id="show">
<div id='myDiv'>Name: <!-- want to display the name here -->
</div>
</p>
</body>
<script type="text/javascript">
    function getName()
    {   
        var name = window.location.href.split("?name=")[1].s‌​plit("+").join(" ");
        var fieldNameElement = document.getElementById('myDiv');
        var oldText=fieldNameElement.innerHTML;
        fieldNameElement.innerHTML = oldText+' '+name;
    }
</script>
</html>

至少在 Chrome 上对我有用

如果url中有更多元素,可以使用split获取“&”之间的元素

问候

【讨论】:

  • 既然可以使用 3 个变量来获取名称,为什么还要使用它呢? var name = window.location.href.split("?name=")[1];
  • 是的,您的解决方案更有效。我用你的编辑我的,谢谢!
  • 谢谢...此代码正在运行...但问题是它不打印空格。假设我输入“Danny Boyle”。它正在显示“Danny+Boyle”。
  • 我编辑了我的响应替换了这一行: var name = window.location.href.split("?name=")[1] 对于这一行: var name = window.location.href.split ("?name=")[1].split("+").join(" ");此更改将替换“”的所有“+”
猜你喜欢
  • 1970-01-01
  • 2014-05-15
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 2013-01-24
  • 2014-01-12
  • 2017-05-22
相关资源
最近更新 更多