JavaScript中的FormData類型示例詳解
前言:
在 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)
- 文件上傳:
FormData
是上傳文件的推薦方式,支持多文件(files[0]
,files[1]
...)。 - Content-Type:瀏覽器會(huì)自動(dòng)設(shè)置
Content-Type: multipart/form-data
并附加邊界參數(shù),無需手動(dòng)指定。 - 兼容性:現(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)文章
IE中直接運(yùn)行顯示當(dāng)前網(wǎng)頁(yè)中的圖片 推薦
IE中直接運(yùn)行顯示當(dāng)前網(wǎng)頁(yè)中的圖片 推薦...2006-08-08javascript時(shí)間戳和日期字符串相互轉(zhuǎn)換代碼(超簡(jiǎn)單)
下面小編就為大家?guī)硪黄猨avascript時(shí)間戳和日期字符串相互轉(zhuǎn)換代碼(超簡(jiǎn)單)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06javascript和jquery實(shí)現(xiàn)設(shè)置和移除文本框默認(rèn)值效果代碼
這篇文章主要介紹了javascript和jquery實(shí)現(xiàn)設(shè)置和移除文本框默認(rèn)值效果代碼,本文實(shí)現(xiàn)的是類似html5 placeholder(空白提示)一種效果,需要的朋友可以參考下2015-01-01js 替換功能函數(shù),用正則表達(dá)式解決,js的全部替換
js 替換功能函數(shù),用正則表達(dá)式解決,js的全部替換,學(xué)習(xí)js的朋友可以參考下。2010-12-12JavaScript交換變量的常用方法小結(jié)【4種方法】
這篇文章主要介紹了JavaScript交換變量的常用方法,結(jié)合實(shí)例形式總結(jié)分析了JavaScript交換變量的4種實(shí)現(xiàn)方法與操作注意事項(xiàng),需要的朋友可以參考下2020-05-05