单击表单的“提交”按钮后获取URL

时间:2019-05-03 13:36:09

标签: javascript html5 window.location

我有一个表单,我想在单击“提交”按钮后检索它的URL。

到目前为止,我所做的是通过JavaScript <form>方法提交.submit(),然后使用window.location.search将URL存储到变量中,然后我也alert()对其进行了<< br />
第一次填写表单时,警报什么都不会显示,而第二次填写时,它会返回我第一次填写的值。

注意:点击提交按钮后,我需要停留在同一页面上。

编辑:首先发生警报,​​然后提交表单,并将变量附加到URL。

这是我的代码供参考:

<html>
    <body>
        <div>
            <h1>Form 1</h1>
            <form id="form1" method="GET">
                Number 1:<input type="text" id="num1" name="num1">
                <br>
                Number 2:<input type="text" id="num2" name="num2">
                <br>
                Number 3:<input type="text" id="num3" name="num3">
                <br>
                Number 4:<input type="text" id="num4" name="num4">
                <br>
                <button id="sub1" onclick="submitFunc()">Submit</button>
            </form>
        </div>
        <script>
            function submitFunc()
            {
                document.getElementById("form1").submit();
                var loc = window.location.search;
                alert(loc);
            }
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

我认为window.location.search不会成功。 取而代之的是,您可以随时直接从表单中获取数据并搜索查询,如下所示:

document.getElementById("myForm").addEventListener('submit', (ev) => {
  //Optional, prevents redirect
  ev.preventDefault()
  
  //ev.currentTarget is the form element
  var data = new FormData(ev.currentTarget);

  //modification of the code from this answer: https://stackoverflow.com/a/24964658/7448536
  var queryParts = [];
  var entries = data.entries()
  for(var pair of entries)
    queryParts.push(encodeURIComponent(pair[0]) + "=" + encodeURIComponent(pair[1]))
  var query = queryParts.join("&")
  var loc = window.location;
  //reassemble the url
  var url = loc.protocol+'//'+loc.host+loc.pathname+'?'+query
  console.log(url)
})
<form id="myForm">
  <input name="test" type="text">
  <input name="example" type="text">
  <button type="submit">Submit</button>
</form>

相关问题