【问题标题】:Javascript form submitting with multiple links带有多个链接的 Javascript 表单提交
【发布时间】:2011-09-02 10:09:56
【问题描述】:

我为这个问题简化了我的代码,但在我的最终 web 应用程序中,一个页面上有大约 100 个表单,而不是这里的两个。我的问题是让我的链接使用 javascript 提交表单的最佳方法是什么。我现在所拥有的显然不起作用,因为有多个名为 supporttype 的字段。对于大约 100 个表格的大规模执行我想做的事情的最佳方法是什么。

<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
function getsupport ( selectedtype )
{
  document.albumdl.supporttype.value = selectedtype ;
  document.albumdl.submit() ;
}
-->
</script>
</head>
<body>


<form name="albumdl" method="post" action="processLinks.php">
<input type="hidden" name="supporttype" />
<a href="javascript:getsupport('form1')">Form1 </a>
</form>

<form name="albumdl" method="post" action="processLinks.php">
<input type="hidden" name="supporttype" />
<a href="javascript:getsupport('form2')">From2</a>
</form>





</body>
</html>

【问题讨论】:

    标签: javascript forms post hyperlink


    【解决方案1】:

    您可以动态构造表单:

    function getSupport (type) {
        var f = document.createElement('form'),
        input = document.createElement('input');
        f.setAttribute('action', 'processLinks.php');
        f.setAttribute('method', 'post');
    
        input.setAttribute('name', 'supporttype');
        input.value = type;
    
        f.appendChild(input);
        f.submit();
     }
    

    【讨论】:

    • 如果你发现自己在写 hack 来做这样的 post 请求,那意味着服务器部分一定有一些设计问题。
    【解决方案2】:

    最简单的方法 - 将值 form1 和 form2 放入相应输入的值中:

    <form name="albumdl" method="post" action="processLinks.php">
    <input type="hidden" name="supporttype" value="form1" />
    <a href="javascript:submitForm(this)">Form1 </a>
    </form>
    
    <form name="albumdl" method="post" action="processLinks.php">
    <input type="hidden" name="supporttype" value="form2" />
    <a href="javascript:submitForm(this)">From2</a>
    </form>
    

    然后编写泛型JS提交最接近点击链接的表单:

    function getsupport ( link ) {
        var form = link.parentNode;
        while (form.tagName != "FORM") {
            form = form.parentNode;
        }
        form.submit();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 2013-06-03
      • 2012-11-22
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 2019-11-08
      相关资源
      最近更新 更多