【问题标题】:Submit current page URL as hidden field with multiple forms on same page (Javascript)将当前页面 URL 作为隐藏字段提交,同一页面上有多个表单(Javascript)
【发布时间】:2020-02-10 13:45:11
【问题描述】:

我正在一个网站上设置一些表单,其中同一个表单会在一个页面上出现多次(这就是为什么我不能在这里使用getElementById)。

我已经尽我所能将当前 URL 作为隐藏字段传递,但我无法弄清楚。感谢您的帮助!

HTML

<form>
    <input type="email" name="email-address" placeholder="Your work email" />
    <input type="button" class="btn btn-inline" value="Submit info" />
    <input type="hidden" name="convertURL" value="" />
</form>

当前脚本

<script>
    document.getElementsByName("convertURL").value = window.location.href;
</script>

表单提交脚本

如果有帮助,这就是表单的提交方式:

<script>
$('input[type="button"]').click(function(e){
    e.preventDefault();
    $.ajax({
        url:'https://examplesite.com/',
        type:'post',
        data:$(this.form).serialize(),
        success:function(){
          window.location = "/success";
        }
    });
});</script>

【问题讨论】:

  • 表单是否真的提交了,只是没有 URL 的值?
  • 是的!其他一切都运行良好。
  • 我不认为getElementByName 是一个函数。有一个 getElementsByName 函数返回一个集合,其中包含与该名称匹配的所有元素,但我认为这行不通。
  • 尝试使用document.getElementsByName,然后循环遍历它们并添加值。
  • 刚刚用 .getElementsByName 编辑了我的原始帖子,但这不起作用

标签: javascript html forms dom


【解决方案1】:

如果你使用 jquery,这会解决它。

$('[name=convertURL]').val(window.location.href);

【讨论】:

    【解决方案2】:
    $('input[type="button"]').click(function(e){ e.preventDefault(); 让 currentUrl = window.location.href; 让数据 = $(this.form).serializeArray(); //从表单中删除输入并附加如下网址, data.push({name: 'convertURL', value: currentUrl}); $.ajax({ url:'https://examplesite.com/', 类型:'发布', 数据:数据, 成功:函数(){ window.location = "/成功"; } }); });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多