简体   繁体   中英

Getting a form's submit URL as a relative url?

Let's say I have a form located at:

http://www.mysite.com/some/place/some/where/index.php

And I have this form:

<form action="submit.php"> ... </form>

If I do this:

$("form").attr("action");

I will get:

submit.php

What is a foolproof way to get the action from the form, so that it includes the entire URL:

http://www.mysite.com/some/place/some/where/submit.php

?

Try

$("form").prop("action");

or (assuming your form is in the same folder as the page and the page URL ends with /something)

var loc = location.href;
var page = loc.substring(0,loc.lastIndexOf("/")+1)+
  $("form").attr("action");

Handle query strings and hashes especially for Quentin:

Live Demo

var loc = location.origin + location.pathname;
var action = $("form").attr("action").split("/").pop();
var page = loc.substring(0,loc.lastIndexOf("/"))+"/"+action;
var el = document.createElement('a');
el.href = $("form").prop("action");

alert(el.href);

Chrome adjusts the href to give the absolute url, not sure with other browsers

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