Make a link use POST instead of GET

2019-01-02 16:53发布

I'm not sure if this is even possible. But I was wondering if anyone knows how to make a hyperlink pass some variables and use POST (like a form) as opposed to GET.

9条回答
倾城一夜雪
2楼-- · 2019-01-02 17:54

HTML + JQuery: A link that submits a hidden form with POST.

Since I spent a lot of time to understand all these answers, and since all of them have some interesting details, here is the combined version that finally worked for me and which I prefer for its simplicity.

My approach is again to create a hidden form and to submit it by clicking a link somewhere else in the page. It doesn't matter where in the body of the page the form will be placed.

The code for the form:

<form id="myHiddenFormId" action="myAction.php" method="post" style="display: none">
  <input type="hidden" name="myParameterName" value="myParameterValue">
</form>

Description:

The display: none hides the form. You can alternatively put it in a div or another element and set the display: none on the element.

The type="hidden" will create an fild that will not be shown but its data will be transmitted to the action eitherways (see W3C). I understand that this is the simplest input type.

The code for the link:

<a href="" onclick="$('#myHiddenFormId').submit(); return false;" title="My link title">My link text</a>

Description:

The empty href just targets the same page. But it doesn't really matter in this case since the return false will stop the browser from following the link. You may want to change this behavior of course. In my specific case, the action contained a redirection at the end.

The onclick was used to avoid using href="javascript:..." as noted by mplungjan. The $('#myHiddenFormId').submit(); was used to submit the form (instead of defining a function, since the code is very small).

This link will look exactly like any other <a> element. You can actually use any other element instead of the <a> (for example a <span> or an image).

查看更多
素衣白纱
3楼-- · 2019-01-02 18:00

You can use javascript functions. JQuery has a nice post function built in if you decide to use it:

JQuery Post

<script language="javascript"> 

   function DoPost(){
      $.post("WhateverPage.php", { name: "John", time: "2pm" } );  //Your values here..
   }

</script>


<a href="javascript:DoPost()">Click Here</A> 
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 18:00

Another working example, using similar approach posted : create a html form, use javascript to simulate the post. This does 2 things : post data to a new page and open it in a new window/tab.

HTML

<form name='myForm' target="_blank" action='newpage.html' method='post'>
<input type="hidden" name="thisIsTheParameterName" value="testDataToBePosted"/>
</form>

JavaScript

document.forms["myForm"].submit();
查看更多
登录 后发表回答