html 按钮可以执行 POST 请求吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16036041/
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
Can a html button perform a POST request?
提问by dorafmon
I want a submit type button to send a POST request.
我想要一个提交类型按钮来发送 POST 请求。
I am thinking about something like this:
我在想这样的事情:
<form action = "" method = "post">
<button>Upvote</button>
<form>
where the string "Upvote" will be send as a name in the POST request.
其中字符串“Upvote”将作为 POST 请求中的名称发送。
I know this is not working, and I know there are ways using AJAX(javascript) but I am fairly new to this area. I am just wondering if this is possible in general.
我知道这行不通,我知道有一些方法可以使用 AJAX(javascript),但我对这个领域还很陌生。我只是想知道这通常是否可行。
Update
更新
Someone suggest that using <input>
tag, I used it. The problem is it generate a GET rather than a POST.
有人建议使用<input>
标签,我使用了它。问题是它生成的是 GET 而不是 POST。
采纳答案by Filip Minx
This can be done with an input element of a type "submit". This will appear as a button to the user and clicking the button will send the form.
这可以通过“提交”类型的输入元素来完成。这将显示为用户的按钮,单击该按钮将发送表单。
<form action="" method="post">
<input type="submit" name="upvote" value="Upvote" />
</form>
回答by Quentin
You need to give the button a name and a value.
您需要为按钮指定名称和值。
No control can be submitted without a name, and the content of a button element is the label, not the value.
没有名称就不能提交任何控件,按钮元素的内容是标签,而不是值。
<form action="" method="post">
<button name="foo" value="upvote">Upvote</button>
</form>
回答by Jasper Lichte
You can do that with a little help of JS. In the example below, a POST request is being submitted on a button click using the fetch method:
你可以在 JS 的帮助下做到这一点。在下面的示例中,使用 fetch 方法在单击按钮时提交 POST 请求:
const button = document.getElementById('post-btn');
button.addEventListener('click', async _ => {
try {
const response = await fetch('yourUrl', {
method: 'post',
body: {
// Your body
}
});
console.log('Completed!', response);
} catch(err) {
console.error(`Error: ${err}`);
}
});
<button id="post-btn">I'm a button</button>
回答by UltraInstinct
You can:
你可以:
- Either, use an
<input type="submit" ..>
, instead of that button. - or, Use a bit of javascript, to get a hold of form object (using name or id), and call
submit(..)
on it. Eg:form.submit()
. Attach this code to the button click event. This will serialise the form parameters and execute a GET or POST request as specified in the form's method attribute.
- 或者,使用
<input type="submit" ..>
, 而不是那个按钮。 - 或者,使用一些 javascript 来获取表单对象(使用名称或 ID),并调用
submit(..)
它。例如:form.submit()
。将此代码附加到按钮单击事件。这将序列化表单参数并执行表单的方法属性中指定的 GET 或 POST 请求。