【发布时间】:2014-12-16 04:08:19
【问题描述】:
我似乎无法弄清楚为什么会这样。任何帮助,将不胜感激。我有一个包含两个字段的 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 中设置输入字段的值。
-
您的
<script>document.forms["invoice"].submit();</script>可能在您的<head><script> document.invoice.x.value = "1"; document.invoice.y.value = "2"; </script></head>执行之前执行。尝试在设置值后将脚本与.submit()组合起来。 -
谢谢肖恩。这正是发生的事情。一旦我实施了您的建议,它就起作用了!亚历克西斯,这通常不是这样做的,但我们必须根据我们的申请情况。
-
@firpo ,如果它解决了您的问题,您可以接受答案好吗?这样未来的访问者也将得到正确的答案。
-
像
document.getElementsByName("x").value="1"一样使用document.getElementsByName
标签: javascript php jquery forms