简体   繁体   English

使用 JavaScript 在提交时获取从表单生成的 URL

[英]Get the URL generated from a form on submit with JavaScript

Is it possible to catch the URL generated from a form when firing its 'submit' event?是否可以在触发其“提交”事件时捕获从表单生成的 URL?

I know I can generate the URL from data我知道我可以从数据生成 URL

I'm not talking about form's action URL我不是在谈论表单的操作 URL

I mean the ?field=value&other-input-name=value& ... part我的意思是?field=value&other-input-name=value& ...部分

Scenario:设想:

We have a form and a JavaScript script which sends an Ajax request to a PHP script.我们有一个表单和一个 JavaScript 脚本,它向 PHP 脚本发送 Ajax 请求。

I usually do like this:我通常这样做:

  • Register for the form's submit event注册表单的提交事件
  • Prevent the default behavior防止默认行为
  • Construct a URL from data从数据构造 URL
  • Open an HTTP request with the constructed URL使用构造的 URL 打开 HTTP 请求

Now, I was wondering, when firing 'submit' normally (on non-Ajax requests) the URL gets constructed by the form, which then uses that URL to send data to the PHP counterpart.现在,我想知道,当(在非 Ajax 请求上)正常触发“提交”时,URL 由表单构造,然后使用该 URL 将数据发送到 PHP 对应方。

How can I 'catch' that URL?我怎样才能“抓住”那个网址? There aren't any clues from the event itself which doesn't seem to store it, or at least I haven't been able to find it.事件本身没有任何线索似乎没有存储它,或者至少我无法找到它。

It must be somewhere!它一定在某个地方!

This is possible and easy with the objects URLSearchParams and FormData .这对于对象URLSearchParamsFormData是可能和容易的。

FormData is an object representation of a form, for using with the fetch API. FormData是表单的对象表示,用于与fetch API 一起使用。 It can be constructed from an existing element like this:它可以从现有元素构建,如下所示:

let form = document.forms[0];
let formData = new FormData(form);

Then comes the URLSearchParams object, which can be used to build up query strings:然后是URLSearchParams对象,可用于构建查询字符串:

let search = new URLSearchParams(formData);

and now all you need to do is call the toString function on the search object:现在您需要做的就是在搜索对象上调用 toString 函数:

let queryString = search.toString();

Done!完毕!

If you mean getting the form's action URL, that URL can be retrieved like this:如果您的意思是获取表单的操作 URL,则可以像这样检索该 URL:

document.getElementById("form-id").action

If you are using jQuery and assuming you are doing an Ajax request, it would be like this:如果您正在使用 jQuery 并假设您正在执行 Ajax 请求,它将是这样的:

var el = $('#form-id');
$.ajax({
    type: el.attr('method'),
    url: el.attr('action'),
    data: el.serialize(),
    context: this
}).done(callback);

To put it simply, you can't.简单地说,你不能。 The best you can do is to collect the form field values yourself, or using jQuery's .serialize() function, which returns those values exactly as you'd expect:您能做的最好的事情是自己收集表单字段值,或者使用 jQuery 的 .serialize() 函数,它会完全按照您的预期返回这些值:

name=value&name2=value2

As already stated, you cannot get the generated URL containing the form values that the browser generates, but it is very easy to construct it yourself.如前所述,您无法获得包含浏览器生成的表单值的生成 URL,但自己构建它非常容易。

If you are using jQuery then use serialize().如果您使用 jQuery,请使用 serialize()。 If not, refer to the post Getting all form values by JavaScript .如果没有,请参阅通过 JavaScript 获取所有表单值一文

 var targetForm = $('#myForm'); var urlWithParams = targetForm.attr('action') + "?" + targetForm.serialize(); alert(urlWithParams);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form action="/search/" id="myForm" method="get"> <input name="param1" type="hidden" value="1"> <input name="param2" type="hidden" value="some text"> </form>

You can use javascript to generate it:您可以使用 javascript 来生成它:

<script>
function test(frm) {
  var elements = frm.elements;
  var url = "?";
  for(var i=0;i<elements.length;i++) {
    var element = elements[i];
    if (i > 0) url += "&";
    url += element.name;
    url += "=";
    if (element.getAttribute("type") == "checkbox") {
      url += element.checked;
    } else {
      url += element.value;
    }
  }
  console.log(url);
  return false;
}
</script>

<form onsubmit='return test(this);'>
<input name=field1 value='123'>
<input type=checkbox name=field2 checked>

<input type=submit>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM