【问题标题】:form fields not passing through when submit is done via javascript通过javascript完成提交时表单字段未通过
【发布时间】: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 中设置输入字段的值。
  • 您的&lt;script&gt;document.forms["invoice"].submit();&lt;/script&gt; 可能在您的&lt;head&gt;&lt;script&gt; document.invoice.x.value = "1"; document.invoice.y.value = "2"; &lt;/script&gt;&lt;/head&gt; 执行之前执行。尝试在设置值后将脚本与.submit() 组合起来。
  • 谢谢肖恩。这正是发生的事情。一旦我实施了您的建议,它就起作用了!亚历克西斯,这通常不是这样做的,但我们必须根据我们的申请情况。
  • @firpo ,如果它解决了您的问题,您可以接受答案好吗?这样未来的访问者也将得到正确的答案。
  • document.getElementsByName("x").value="1"一样使用document.getElementsByName

标签: javascript php jquery forms


【解决方案1】:

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

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

并提交表单使用:

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

【讨论】:

    【解决方案2】:

    Please check this

    在正文下方使用关闭标签check This

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

    或者使用 jQuery

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

    【讨论】:

    • 他没有标记 jquery。
    • 我还不知道 jQuery,但希望尽快进入。谢谢。
    猜你喜欢
    • 2012-04-29
    • 2019-04-19
    • 1970-01-01
    • 2016-04-04
    • 2018-08-18
    • 1970-01-01
    • 2011-04-17
    相关资源
    最近更新 更多