我有两个 html 表单,我正在将输入数据从一个 html 表单发布到另一个 html 表单。我想检索使用表单 1 发布到表单 2 的变量值。
<form name ="form1" id ="form1" method ="post" action = "form2.html>
<input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>
我的问题是,一旦使用 javascript 从表单 1 发布到表单 2,如何获取表单 2 上隐藏变量 sendToForm2 的值。
最佳答案
您不能使用 POST
方法,因为对于 plain HTML 页面,您没有 HTTP header ,只有 HTML 页面代码本身和 URL(带有查询字符串)。
你可以做的是使用 GET
而不是 POST
然后解析查询字符串以提取它们:
<form name ="form1" id ="form1" method ="GET" action = "form2.html>
<input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>
然后在您的 form2.html
中,您可以使用此函数(来自 this post on SO)来解析查询字符串:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
现在(让我使用 jQuery)你可以用这个访问它们:
<form ...>
<input id ="sentFromForm1" type ="hidden" value =""/>
</form>
</script>
$("#sentFromForm1").val(getParameterByName("sendToForm2"));
</script>
关于javascript - 如何使用 javascript 从发布的 html 表单中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22609250/