返回

Form表单提交不跳转

前端

在 Hybrid App 中,如果使用传统的 Form 表单提交方式,页面会发生跳转,这与 Native App 的行为不一致。为了实现 Form 表单提交不跳转,我们需要使用特殊的编码方式和设置。

enctype 属性

enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。默认情况下,表单数据会编码为 "application/x-www-form-urlencoded"。这种编码方式会将空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 代码。

application/x-www-form-urlencoded 格式

application/x-www-form-urlencoded 是最常见的表单数据编码格式。这种格式将表单数据编码成一系列的键值对,每个键值对由一个名称和一个值组成,名称和值之间用等号 (=) 连接,键值对之间用 & 符号连接。例如,以下表单数据:

name=John Doe
age=30

会被编码为:

name=John+Doe&age=30

实现 Form 表单提交不跳转

为了实现 Form 表单提交不跳转,我们需要在 Form 表单中设置 enctype 属性为 "application/x-www-form-urlencoded"。同时,我们需要使用 Ajax 技术来提交表单数据。Ajax 技术可以实现异步请求,即在不刷新页面的情况下向服务器发送请求并接收响应。

以下是一个实现 Form 表单提交不跳转的示例代码:

<form action="submit.php" method="post" enctype="application/x-www-form-urlencoded">
  <input type="text" name="name" placeholder="Name">
  <input type="number" name="age" placeholder="Age">
  <button type="submit">Submit</button>
</form>
const form = document.querySelector('form');

form.addEventListener('submit', (event) => {
  event.preventDefault();

  const data = new FormData(form);

  fetch('submit.php', {
    method: 'POST',
    body: data,
  }).then((response) => {
    if (response.ok) {
      alert('提交成功!');
    } else {
      alert('提交失败!');
    }
  });
});

通过这种方式,我们可以实现 Form 表单提交不跳转,并且可以异步地向服务器发送请求并接收响应。