formdata 表单_使用JavaScript FormData API创建自定义表单

formdata 表单

Building a form is easy to do as long as you don’t have an edge case. Then the bacon fat goes down the drain and your pipes are ruined. So you sometimes need some extra tools in your toolbelt to deal with it. The FormData API can be one of your tools.

只要没有边缘情况,构建表单就很容易。 然后,培根脂肪顺流而下,您的烟斗被毁了。 因此,有时您的工具栏中需要一些其他工具来处理它。 FormData API可以是您的工具之一。

核心FormData API (The Core FormData API)

FormData has a lot of features but the only method that works across all browsers is append. Let’s say we want to create a social application for people to share their bacon pictures. Here we’ll create a form that allows users to send a picture with a title and the author’s name. Our HTML markup will look like this:

FormData具有很多功能,但是在所有浏览器中都有效的唯一方法是append 。 假设我们要创建一个社交应用程序,以便人们共享他们的培根图片。 在这里,我们将创建一个表格,允许用户发送带有标题和作者姓名的图片。 我们HTML标记如下所示:

<input type="text" name="author"  id="author-input" />
<input type="text" name="title" id="title-input" />
<input type="file" name="picture" id="picture-input" />
<button id="submit-button">SUBMIT</button>

To handle our data we can create the following code:

为了处理我们的数据,我们可以创建以下代码:

Module: bacon-form.js
模块:bacon-form.js
const inputs = document.getElementsByTagName('input');
// This object will keep track of the changes of inputs
const applicationState = {
  title: "",
  author: "",
  picture: ""
}

document.getElementById('submit-button').onclick = async () => {
  // We create a new form object
  const form = new FormData();
  // we append each element to the form
  form.append('title', applicationState.title);
  form.append('author', applicationState.author);
  form.append('picture', applicationState.picture);

  const res = await fetch('https://postman-echo.com/post', {
    method: 'POST',
    mode: 'no-cors',
    body: form
  });
  // ... Do something with the response
}

// The rest of this code is functional
// It is not directly related to FormData

// This for loop reflects input changes to the application's state
for (let i = 0; i < inputs.length; i++) {
  const input = inputs[i]
  const inputName = input.name

  input.onchange = (e) => {
    let value = e.target.value
    // updating the application state according to the input the user interacted with
    if (inputName === 'picture' && e.target.files[0]) {
      setPicture(e.target.files[0]);
    } else {
      applicationState[inputName] = value;
    }
  };
}
// setPicture takes a file reads it as a base64URL and assigns that value to application.picture
const setPicture = (file) => {
  const fr = new FileReader();
  // Reading the data and encoding it as base64 to send it to the server
  fr.readAsDataURL(file);
  // When the data is done loading we assign it to picture
  fr.onloadend = (fileData) => {
    applicationState.picture = fileData.target.result;
  }
}

If this is our input:

如果这是我们的输入:

Then we press the submit button we’ll roughly get the following request headers:

然后,按下提交按钮,我们将大致获得以下请求标头:

{
  "Accept-Encoding": "gzip, deflate, br",
  "Connection": "keep-alive",
  "Content-Length": "4369",
  "Content-Type": "multipart/form-data",
  "Host": "postman-echo.com",
  "Origin": "null",
  "Sec-Fetch-Mode": "no-cors",
  "Sec-Fetch-Site": "cross-site"
}

And the following body:

和以下主体:

{
  "title": "Alligator Bacon",
  "author": "Jack Misteli",
  "picture": "data:text/javascript;base64,iVBORw0KGgoAA......."
}

Please note that FormData constructor can take form data as an argument. So you could do:

请注意, FormData构造函数可以将表单数据作为参数。 因此,您可以执行以下操作:

Module: regular-form.html
模组:regular-form.html
<form id="user-form">
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="file" name="picture" id="picture-input"/>
  <input type="submit">
</form>
<script>
  document.getElementById('user-form').onsubmit = async function (e) {
    e.preventDefault();
    // here `this` is the user-form HTML element
    const form = new FormData(this);
    ///... send form to server
  }
</script>

Another important gotcha, is that append does not overwrite a key if it already exists.

另一个重要的陷阱是, append不会覆盖已存在的密钥。

Module: double-bacon-form.js
模组:double-bacon-form.js
const form = new FormData();
form.append('baconType', 'pork');
form.append('baconType', 'vegan');
// When you send your form it will look like this:
// {
//  baconType: pork
//  baconType: vegan
//}

If you want to overwrite a key value you will have to use other functions.

如果要覆盖键值,则必须使用其他功能。

进阶表格 (Advanced Forms)

The FormData constructor and the append method are available in all browsers. Most of the other methods are pretty self-descriptive:

在所有浏览器中都可以使用FormData构造函数和append方法。 其他大多数方法都是非常自我描述的:

  • FormData.has(key): Checks if the key exists in the form.

    FormData.has(key) :检查密钥是否存在于表单中。

  • FormData.set(key, value): Changes the value associated to the key.

    FormData.set(key, value) :更改与键关联的值。

  • FormData.delete(key): Deletes the entry associated with the key.

    FormData.delete(key) :删除与键关联的条目。

  • FormData.get(key): Accesses the first value associated with the key.

    FormData.get(key) :访问与键关联的第一个值。

  • FormData.getAll(key): Creates an array of all the values associated with a key.

    FormData.getAll(key) :创建一个与键关联的所有值的数组。

  • FormData.keys(), FormData.values(), FormData.entries(): Iterators used to get all the keys, associated values or just entries of the FormData.

    FormData.keys()FormData.values()FormData.entries() :用于获取所有键,关联值或FormData条目的迭代器。

🥓 That’s it if you have any questions you can fire them up on Twitter with a link to the article and I’ll do my best to answer them!

if就是这些,如果您有任何问题,可以通过指向文章的链接在Twitter上发布,我会尽力回答!

翻译自: https://www.digitalocean.com/community/tutorials/js-formdata

formdata 表单

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值