最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Relative form action resolves to absolute URL? - Stack Overflow

matteradmin2PV0评论

I am trying to get the actual string that is placed in a form action. The problem is when I do this, the action property resolves to an absolute path even though a relative path is in the HTML. How do I get the actual string that is in the action property?

Here is a sample of what I am referring to: /

I am trying to get the actual string that is placed in a form action. The problem is when I do this, the action property resolves to an absolute path even though a relative path is in the HTML. How do I get the actual string that is in the action property?

Here is a sample of what I am referring to: http://jsfiddle/MSY4s/

Share asked Oct 4, 2012 at 14:12 BasemBasem 6141 gold badge10 silver badges25 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

If you're already using jquery, I would use the .attr function rather than extracting the DOM element from the jQuery object. Like so:

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

That should give you literally what is in the action attribute. In the example you provided, that should look like "/somewhere". The second example in your jFiddle will show a full path since that's what is in the action attribute.

Relative URLs are always resolved to absolute ones on the base of the current document’s URL.

Try this:

Give both of your forms ids:

<form id="form1" action="/somewhere" method="post">
<input type="text" name="test" />
</form>

<form id="form2" action="https://fiddle.jshell/somewhere2" method="post">
<input type="text" name="test" />
</form>​

Then using these ids you can get the action attribute of each form:

$('#form1').attr('action');

$('#form2').attr('action');

You can also set the action attributes using the same tags:

$('#form1').attr('action', '[New Action Value]');

$('#form2').attr('action', '[New Action Value]');

Hope this helps.

Post a comment

comment list (0)

  1. No comments so far