简体   繁体   中英

How to get the final submission URL for a HTML form programmatically in Javascript

I have a simple HTML form which uses GET instead of POST.

<form id="form" action="https://www.example.com/search" method="GET">
    <input name="foo" type="text" />
    <input name="bar" type="text" />
    <input type="submit" value="submit" />
</form>

When the user hits 'Submit', I'd expect them to be directed to an URL like http://www.example.com/search?foo=abc&bar=123 , ie the action URL with a query string appended.

Is there an easy way to get this final form URL with query parameters programmatically in Javascript, without having to construct it? Something like document.getElementById('form').submissionURL

Using Jquery serialize you should be able to get this done

$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
  var submitURL=$( '#form' ).attr( 'action' );
  if(submitURL.indexOf("?")==-1)
  {
  console.log( submitURL+'?'+$( '#form' ).serialize() );
  }
  else
  {
  console.log( submitURL+'&'+$( '#form' ).serialize() );
  }

});

https://jsfiddle.net/zrypfens/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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