新聞中心
TypeScript FormData詳解

1. 什么是FormData?
FormData是一個(gè)用于封裝表單數(shù)據(jù)的類(lèi),通常用于在AJAX請(qǐng)求中發(fā)送表單數(shù)據(jù),它可以用來(lái)處理文件上傳和表單數(shù)據(jù)。
2. FormData的基本用法
2.1 創(chuàng)建FormData對(duì)象
要?jiǎng)?chuàng)建一個(gè)FormData對(duì)象,首先需要獲取表單元素,然后使用FormData構(gòu)造函數(shù)創(chuàng)建一個(gè)新的FormData實(shí)例。
const formElement = document.querySelector('form');
const formData = new FormData(formElement);
2.2 添加表單數(shù)據(jù)
使用append()方法向FormData對(duì)象中添加數(shù)據(jù)。
formData.append('key', 'value');
2.3 添加文件
使用append()方法向FormData對(duì)象中添加文件。
const fileInput = document.querySelector('input[type="file"]');
formData.append('file', fileInput.files[0]);
2.4 刪除數(shù)據(jù)
使用delete()方法從FormData對(duì)象中刪除數(shù)據(jù)。
formData.delete('key');
3. FormData與AJAX請(qǐng)求
3.1 發(fā)送AJAX請(qǐng)求
使用XMLHttpRequest或fetch API發(fā)送AJAX請(qǐng)求,并將FormData對(duì)象作為請(qǐng)求體。
使用XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);
xhr.send(formData);
使用fetch API:
fetch('/api/upload', {
method: 'POST',
body: formData,
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
3.2 接收服務(wù)器響應(yīng)
在服務(wù)器端,可以使用req.body獲取到客戶(hù)端發(fā)送的表單數(shù)據(jù),在Node.js的Express框架中:
app.post('/api/upload', (req, res) => {
const formData = req.body; // 獲取客戶(hù)端發(fā)送的表單數(shù)據(jù)
// ...處理數(shù)據(jù)...
});
分享文章:TypeScriptFormData詳解
標(biāo)題路徑:http://m.fisionsoft.com.cn/article/cdghgeh.html


咨詢(xún)
建站咨詢(xún)
