作为 Web 开发者,我们经常面临这样的挑战:在无法或不适合使用 HTML 表单的情况下,使用 JavaScript 发送 POST 请求来模拟表单提交的功能。为了解决这个问题,我们需要找到一种方法,利用 JavaScript 复制表单提交的行为,目标是准确地将数据发送到服务器并接收响应。
当我们在 HTML 中提交表单时,用户输入的数据会通过 POST 请求发送到服务器。服务器随后处理这些数据并做出相应的响应。
在 JavaScript 中,我们可以向服务器发送 POST 请求来提交数据,这与表单提交非常相似。当我们需要在不要求用户手动提交表单的情况下将数据发送到服务器时,这一功能特别有用。
要在 JavaScript 中发送 POST 请求,我们通常需要指定数据发送的端点以及需要发送的具体数据。
解决方案的 JavaScript 代码: 我们将创建一个 JavaScript 函数,该函数会生成一个隐藏的表单,默认将方法设置为 "post",将操作路径设置为给定的路径,并根据传入的参数对象填充隐藏的输入字段。最后,它会将表单添加到文档主体中并提交它。
示例 1: 让我们创建一个名为 index.html 的文件,我们将构建一个包含单个按钮的简单界面。在这个例子中,我们将点击按钮,并通过 POST 请求向服务器发送数据。
index.html
HTML
“
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
div {
display: flex;
justify-content: center;
margin-top: 5%;
}
button {
padding: 0.6em 1em;
border: 4px solid #fa725a;
transition: ease-in-out 0.3s;
background-color: transparent;
color: #fa725a;
font-weight: bolder;
font-size: 16px;
cursor: pointer;
}
button:hover {
transform: scale(1.2) rotate(10deg);
background-color: #fa725a;
color: white;
}
const send_button = document.getElementById
("send_data");
function postData(path, params, method) {
// 创建表单
const hidden_form = document.createElement(‘form‘);
// 默认设置方法为 post
hidden_form.method = method || ‘post‘;
// 设置路径
hidden_form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hidden_input = document.createElement
(‘input‘);
hidden_input.type = ‘hidden‘;
hidden_input.name = key;
hidden_input.value = params[key];
hiddenform.appendChild(hiddeninput);
}
}
document.body.appendChild(hidden_form);
hidden_form.submit();
}
send_button.addEventListener(‘click‘, () => {
// 调用 postData 函数
postData(‘https://…com/posts‘,
{ title: ‘foo‘, body: ‘bar‘, userId: 1 });
});
`
**输出效果:**
JavaScript post request like a form submit
**示例 2:** 在这个例子中,我们将尝试把一个数组作为值进行发送,具体数据如下所示:
{
title: ‘fruits‘,
names: [‘Apple‘,‘Banana‘,‘Mango‘],
basketId: 1
}
**index.html**
HTML
`
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
div {
display: flex;
justify-content: center;
margin-top: 5%;
}
button {
padding: 0.6em 1em;
border: 4px solid #fa725a;
transition: ease-in-out 0.3s;
background-color: transparent;
color: #fa725a;
font-weight: bolder;
font-size: 16px;
cursor: pointer;
}
button:hover {
transform: scale(1.2) rotate(10deg);
background-color: #fa725a;
color: white;
}