制作 href(锚标签)请求 POST 而不是 GET? [英] Making href (anchor tag) request POST instead of GET?

查看:21
本文介绍了制作 href(锚标签)请求 POST 而不是 GET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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?

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

推荐答案

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

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented 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>

并使用(在纯 JS 中)

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

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

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

这篇关于制作 href(锚标签)请求 POST 而不是 GET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆