Html 制作 href(锚标记)请求 POST 而不是 GET?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20906066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:18:38  来源:igfitidea点击:

Making href (anchor tag) request POST instead of GET?

htmlpostgetanchor

提问by emilly

<a href="employee.action" id="employeeLink">Employee1</a>

when i click the Employee1 link, GET request goes to server. I want to make it POST instead of GET request. Is there a way i can change default GET behaviour of href?

当我单击 Employee1 链接时,GET 请求将发送到服务器。我想让它 POST 而不是 GET 请求。有没有办法可以更改 href 的默认 GET 行为?

Note:- I know it can be done where we can call javascript function on hyperlink click , then create form and submit it. But i am looking where we can mention some attribute in anchor tag to make POST request instead of GET request?

注意:- 我知道我们可以在超链接点击时调用 javascript 函数,然后创建表单并提交它。但是我正在寻找可以在锚标记中提及某些属性以发出 POST 请求而不是 GET 请求的地方?

采纳答案by mplungjan

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

使用 jQuery 非常简单,假设您希望发布的 URL 位于同一服务器上或已实现 CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

如果您坚持使用我强烈反对的框架,请提供一个表格并通过链接提交

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

并使用(在纯 JS 中)

 window.onload=function() {
   document.getElementById("employeeLink").onclick=function() {
     document.getElementById("myForm").submit();
     return false; // cancel the actual link
   }
 }

Without a form we need to make one

没有表格,我们需要制作一个

 window.onload=function() {
   document.getElementById("employeeLink").onclick=function() {
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
     return false; // cancel the actual link
   }
 }

回答by rkawano

To do POSTyou'll need to have a form.

要进行POST,您需要有一个form

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

有一些方法可以使用超链接发布数据,但您需要一些 javascript 和一个表单。

Some tricks: Make a link use POST instead of GETand How do you post data with a link

一些技巧:制作链接使用 POST 而不是 GET以及如何使用链接发布数据

Edit: to load response on a frame you can target your form to your frame:

编辑:要在框架上加载响应,您可以将表单定位到框架:

<form action="employee.action" method="post" target="myFrame">