通过 JavaScript 完成提交时表单字段不会通过

form fields not passing through when submit is done via javascript

本文关键字:字段 表单 JavaScript 提交 通过      更新时间:2023-09-26

我似乎无法弄清楚为什么会发生这种情况。任何帮助将不胜感激。我有一个带有两个字段的 html 表单。当我运行页面并使用提交按钮提交表单时,字段值通过 ok。但是,如果我运行相同的页面并使用此处显示的 javascript 提交,则接收文件显示 x 和 y 的空值。

源文件:

<html>
<head>
<script>
          document.invoice.x.value = "1";
          document.invoice.y.value = "2";
</script>
</head>
<body>
<form method="post" name="invoice" id="invoice" action="process_payment.php">
X: <input type="text" name="x"> Y: <input type="text" name="y">
<script>document.forms["invoice"].submit();</script>
</form>
</body>
</html>

目标文件 (process_payment.php):

<?php
    session_start();
print "<pre>"; print_r($_POST); print("</pre>");
?>

我得到的输出:

Array
(
    [x] => 
    [y] => 
)

你可以在javascript中像这样设置你的值:

document.getElementsByName("x").value="1";
document.getElementsByName("y").value="2";

要提交表格,请使用:

document.forms["invoice"].submit();

请检查此

在正文之前在下面使用 关闭标签 检查此

<script>
      document.invoice.x.value = "1";
      document.invoice.y.value = "2";
</script>

或者使用 jQuery

<script>
          $("[name='x']").val("1");
          $("[name='y']").val("2");
</script>