我不确定这是否可行。但我想知道是否有人知道如何使一个超链接传递一些变量和使用POST(像一个表单)而不是GET。
当前回答
除了使用javascript,还可以使用标签发送隐藏表单。非常简单和小的解决方案。标签可以在html中的任何地方。
<form style="display: none" action="postUrl" method="post"> <button type="submit" id="button_to_link"> </button> . > < /形式 <label style="text-decoration: underline" for="button_to_link">张贴的链接</label>
其他回答
可以使用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();
}
下面是jsFiddle (http://jsfiddle.net/S7zUm/)中的一个例子
您可以创建一个带有隐藏输入的表单,其中包含要发布的值,将表单的动作设置为目标url,并将表单方法设置为发布。然后,当链接被单击时,触发一个提交表单的JS函数。
请看这里的例子。这个例子使用纯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>
除了使用javascript,还可以使用标签发送隐藏表单。非常简单和小的解决方案。标签可以在html中的任何地方。
<form style="display: none" action="postUrl" method="post"> <button type="submit" id="button_to_link"> </button> . > < /形式 <label style="text-decoration: underline" for="button_to_link">张贴的链接</label>
我建议一种更动态的方法,没有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()
})
不需要JavaScript。只是想说清楚一点,因为在这个答案发布的时候,这个问题的所有答案都涉及到以某种方式使用JavaScript。
使用纯HTML和CSS可以很容易地做到这一点,只需创建一个包含要提交的数据的隐藏字段的表单,然后将表单的提交按钮设置为链接的样式。
例如:
.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>
您使用的确切CSS可能会根据站点上常规链接的样式而有所不同。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?