欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中的FormData類型示例詳解

 更新時(shí)間:2025年07月22日 09:13:17   作者:前端_yu小白  
這篇文章主要介紹了JavaScript中FormData類型的相關(guān)資料,JavaScript中的FormData接口用于構(gòu)建和發(fā)送表單數(shù)據(jù)(尤其適合文件上傳),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

前言:

在 JavaScript 中,FormData 是一個(gè)用于構(gòu)建表單數(shù)據(jù)的接口,主要用于通過  XMLHttpRequest 或  fetch API  發(fā)送表單數(shù)據(jù)(尤其是文件上傳)。它提供了一種方便的方式來處理表單字段(包括文件)的鍵值對(duì)。

FormData類型數(shù)據(jù)的結(jié)構(gòu)

看著和Map類型有些相似,因?yàn)閷?shí)現(xiàn)了Symbol[iterator],因此是可迭代對(duì)象。

1. 創(chuàng)建 FormData 對(duì)象

可以通過構(gòu)造函數(shù)直接創(chuàng)建空的 FormData 對(duì)象,或者從 HTML 表單元素初始化:

// 方法1:創(chuàng)建空的 FormData
const formData = new FormData();

// 方法2:從 HTML 表單初始化(自動(dòng)包含表單的所有字段)
const formElement = document.querySelector('form');
const formDataFromForm = new FormData(formElement);

2. 添加數(shù)據(jù)到 FormData

使用 append() 方法添加字段(支持多次添加同名鍵):

const formData = new FormData();

// 添加文本字段
formData.append('username', 'JohnDoe');
formData.append('age', '25');

// 添加文件(通過文件輸入框獲取)
const fileInput = document.querySelector('input[type="file"]');
if (fileInput.files.length > 0) {
  formData.append('avatar', fileInput.files[0]); // 'avatar' 是字段名
}

// 可以添加多個(gè)同名鍵(如多選框)
formData.append('hobbies', 'reading');
formData.append('hobbies', 'gaming');

3. 發(fā)送 FormData 到服務(wù)器

通過 fetch 或 XMLHttpRequest 發(fā)送數(shù)據(jù):

使用 fetch API

fetch('/api/upload', {
  method: 'POST',
  body: formData, // 直接傳遞 FormData 對(duì)象
  // 注意:不要手動(dòng)設(shè)置 Content-Type,瀏覽器會(huì)自動(dòng)添加 multipart/form-data
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

使用 XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log('Upload success:', xhr.responseText);
  }
};
xhr.send(formData);

4. 讀取 FormData 內(nèi)容

雖然 FormData 主要用于發(fā)送數(shù)據(jù),但也可以通過以下方式讀取內(nèi)容:

// 遍歷所有字段
for (const [key, value] of formData.entries()) {
  console.log(key, value);
}

// 獲取單個(gè)字段的值(僅第一個(gè))
const username = formData.get('username');

// 檢查字段是否存在
const hasAge = formData.has('age');

5. 注意事項(xiàng)

  1. 文件上傳FormData 是上傳文件的推薦方式,支持多文件(files[0]files[1]...)。
  2. Content-Type:瀏覽器會(huì)自動(dòng)設(shè)置 Content-Type: multipart/form-data 并附加邊界參數(shù),無需手動(dòng)指定。
  3. 兼容性:現(xiàn)代瀏覽器均支持 FormData,但在舊版 IE 中可能需要 polyfill(如 formdata-polyfill)。

完整示例:

<form id="myForm">
    <input type="text" name="username" placeholder="Username">
    <input type="file" name="avatar">
    <button type="submit">Submit</button>
  </form>
  
  <script>
    document.getElementById('myForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const formData = new FormData(e.target);
      formData.append('username', 'some data'); ///測(cè)試append方法添加同名鍵

      console.log('FormData:', formData);
      for (const [key, value] of formData) {
        console.log(key, value)
      }
  
      try {
        const response = await fetch('/api/upload', {
          method: 'POST',
          body: formData,
        });
        const result = await response.json();
        console.log('Success:', result);
      } catch (error) {
        console.error('Error:', error);
      }
    });
  </script>

總結(jié) 

到此這篇關(guān)于JavaScript中的FormData類型示例詳解的文章就介紹到這了,更多相關(guān)JS中FormData類型內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論