Javascript 使链接使用 POST 而不是 GET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3915917/
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-23 06:37:37  来源:igfitidea点击:

Make a link use POST instead of GET

javascripthtmlhttp

提问by Elliot

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.

我不确定这是否可能。但我想知道是否有人知道如何让超链接传递一些变量并使用 POST(如表单)而不是 GET。

采纳答案by Palantir

You create a form with hidden inputs that hold the values to be posted, set the actionof the form to the destination url, and the form method to post. Then, when your link is clicked, trigger a JS function that submits the form.

您创建一个带有隐藏输入的表单,其中包含要发布的值,将表单的操作设置为目标 url,并将表单方法设置为post。然后,当您的链接被点击时,触发一个提交表单的 JS 函数。

See here, for an example. This example uses pure JavaScript, with no jQuery — you could choose this if you don't want to install anything more than you already have.

请参见此处,以获取示例。此示例使用纯 JavaScript,没有 jQuery — 如果您不想安装任何已有的东西,则可以选择此选项。

<form name="myform" action="handle-data.php" method="post">
  <label for="query">Search:</label>
  <input type="text" name="query" id="query"/>
  <button>Search</button>
</form>

<script>
var button = document.querySelector('form[name="myform"] > button');
button.addEventListener(function() {
  document.querySelector("form[name="myform"]").submit();
});
</script>

回答by Ajedi32

You don't need JavaScript for this.Just wanted to make that clear, since as of the time this answer was posted, allof the answers to this question involve the use of JavaScript in some way or another.

为此,您不需要 JavaScript。只是想说清楚,因为在发布此答案时,该问题的所有答案都涉及以某种方式使用 JavaScript。

You can do this rather easily with pure HTML and CSSby creating a form with hidden fields containing the data you want to submit, then styling the submit button of the form to look like a link.

您可以使用纯 HTML 和 CSS轻松完成此操作,方法是创建一个带有隐藏字段的表单,其中包含您要提交的数据,然后将表单的提交按钮样式化为看起来像一个链接。

For example:

例如:

.inline {
  display: inline;
}

.link-button {
  background: none;
  border: none;
  color: blue;
  text-decoration: underline;
  cursor: pointer;
  font-size: 1em;
  font-family: serif;
}
.link-button:focus {
  outline: none;
}
.link-button:active {
  color:red;
}
<a href="some_page">This is a regular link</a>

<form method="post" action="some_page" class="inline">
  <input type="hidden" name="extra_submit_param" value="extra_submit_value">
  <button type="submit" name="submit_param" value="submit_value" class="link-button">
    This is a link that sends a POST request
  </button>
</form>

The exact CSS you use may vary depending on how regular links on your site are styled.

您使用的确切 CSS 可能会有所不同,具体取决于您网站上的常规链接的样式。

回答by AGoodDisplayName

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

您可以使用 javascript 函数。如果您决定使用它,JQuery 内置了一个很好的 post 函数:

JQuery Post

JQuery 帖子

<script language="javascript"> 

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

</script>



<a href="javascript:DoPost()">Click Here</A> 

回答by Majid Fouladpour

This is an old question, but none of the answers satisfy the request in-full. So I'm adding another answer.

这是一个老问题,但没有一个答案完全满足要求。所以我要添加另一个答案。

The requested code, as I understand, should make only one change to the way normal hyperlinks work: the POSTmethod should be used instead of GET. The immediate implications would be:

据我了解,所请求的代码应该只对普通超链接的工作方式进行一项更改:POST应该使用该方法而不是GET. 直接影响将是:

  1. When the link is clicked we should reload the tab to the url of the href
  2. As the method is POST, we should have no query string in the URL of the target page we load
  3. That page should receive the data in parameters (names and value) by POST
  1. 当链接被点击时,我们应该将标签重新加载到 href
  2. 由于方法是POST,我们加载的目标页面的URL中应该没有查询字符串
  3. 该页面应该通过以下方式接收参数(名称和值)中的数据 POST

I am using jquery here, but this could be done with native apis (harder and longer of course).

我在这里使用 jquery,但这可以通过本机 apis 来完成(当然更难更长)。

<html>
<head>
    <script src="path/to/jquery.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {

            $("a.post").click(function(e) {
                e.stopPropagation();
                e.preventDefault();
                var href = this.href;
                var parts = href.split('?');
                var url = parts[0];
                var params = parts[1].split('&');
                var pp, inputs = '';
                for(var i = 0, n = params.length; i < n; i++) {
                    pp = params[i].split('=');
                    inputs += '<input type="hidden" name="' + pp[0] + '" value="' + pp[1] + '" />';
                }
                $("body").append('<form action="'+url+'" method="post" id="poster">'+inputs+'</form>');
                $("#poster").submit();
            });
        });
    </script>
</head>
<body>
    <a class="post" href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Post it!</a><br/>
    <a href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Normal link</a>
</body>
</html>

And to see the result, save the following as reflector.php in the same directory you have the above saved.

并查看结果,将以下内容另存为reflector.php 保存在上述保存的同一目录中。

<h2>Get</h2>
<pre>
<?php print_r($_GET); ?>
</pre>

<h2>Post</h2>
<pre>
<?php print_r($_POST); ?>
</pre>

回答by Quannt

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 表单,使用 javascript 来模拟发布。这有两件事:将数据发布到新页面并在新窗口/选项卡中打开它。

HTML

HTML

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

JavaScript

JavaScript

document.forms["myForm"].submit();

回答by MakisH

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

HTML + JQuery:使用 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: nonehides the form. You can alternatively put it in a div or another element and set the display: noneon the element.

display: none隐藏的形式。您也可以将其放在 div 或其他元素中并display: none在元素上设置。

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.

所述type="hidden"将创建将不会示出的FILD但其数据将被传输到动作eitherways(见W3C)。我知道这是最简单的输入类型。

The code for the link:

链接的代码:

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

Description:

描述:

The empty hrefjust targets the same page. But it doesn't really matter in this case since the return falsewill 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.

href针对同一个页面。但在这种情况下这并不重要,因为这return false将阻止浏览器跟随链接。当然,您可能希望更改此行为。在我的特定情况下,该操作最后包含重定向。

The onclickwas 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).

onclick使用,以避免使用href="javascript:..."由mplungjan指出。所述$('#myHiddenFormId').submit();用于提交表单(而不是限定的函数,因为代码是非常小的)。

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).

此链接看起来与任何其他<a>元素完全一样。您实际上可以使用任何其他元素而不是<a>(例如 a<span>或图像)。

回答by Mahdi Firouzjah

As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:

正如许多帖子中提到的,这不是直接可能的,但是一个简单而成功的方法如下:首先,我们在我们的 html 页面的正文中放置一个表单,它没有任何提交按钮,还有它的输入是隐藏的。然后我们使用一个javascript函数来获取数据并发送表单。这种方法的优点之一是重定向到其他页面,这取决于服务器端代码。代码如下:现在在任何需要“POST”方法的地方:

<script type="text/javascript" language="javascript">
function post_link(data){

    $('#post_form').find('#form_input').val(data);
    $('#post_form').submit();
};
</script>

   <form id="post_form" action="anywhere/you/want/" method="POST">
 {% csrf_token %}
    <input id="form_input" type="hidden" value="" name="form_input">
</form>

<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>

回答by DarkThanos

You can use this jQuery function

你可以使用这个 jQuery 函数

function makePostRequest(url, data) {
    var jForm = $('<form></form>');
    jForm.attr('action', url);
    jForm.attr('method', 'post');
    for (name in data) {
        var jInput = $("<input>");
        jInput.attr('name', name);
        jInput.attr('value', data[name]);
        jForm.append(jInput);
    }
    jForm.submit();
}

Here is an example in jsFiddle (http://jsfiddle.net/S7zUm/)

这是 jsFiddle 中的一个例子(http://jsfiddle.net/S7zUm/

回答by Nimrod

I suggest a more dynamic approach, without html coding into the page, keep it strictly JS:

我建议采用更动态的方法,无需将 html 编码到页面中,严格保持 JS:

$("a.AS-POST").on('click', e => {
  e.preventDefault()
  let frm = document.createElement('FORM')
  frm.id='frm_'+Math.random()
  frm.method='POST'
  frm.action=e.target.href
  document.body.appendChild(frm)
  frm.submit()
})

回答by Shoaib Quraishi

Check this it will help you

检查这个它会帮助你

$().redirect('test.php', {'a': 'value1', 'b': 'value2'});