新聞中心
TypeScript FormData詳解

1. 什么是FormData?
FormData是一個用于封裝表單數(shù)據(jù)的類,通常用于在AJAX請求中發(fā)送表單數(shù)據(jù),它可以用來處理文件上傳和表單數(shù)據(jù)。
2. FormData的基本用法
2.1 創(chuàng)建FormData對象
要創(chuàng)建一個FormData對象,首先需要獲取表單元素,然后使用FormData構(gòu)造函數(shù)創(chuàng)建一個新的FormData實例。
const formElement = document.querySelector('form');
const formData = new FormData(formElement);
2.2 添加表單數(shù)據(jù)
使用append()方法向FormData對象中添加數(shù)據(jù)。
formData.append('key', 'value');
2.3 添加文件
使用append()方法向FormData對象中添加文件。
const fileInput = document.querySelector('input[type="file"]');
formData.append('file', fileInput.files[0]);
2.4 刪除數(shù)據(jù)
使用delete()方法從FormData對象中刪除數(shù)據(jù)。
formData.delete('key');
3. FormData與AJAX請求
3.1 發(fā)送AJAX請求
使用XMLHttpRequest或fetch API發(fā)送AJAX請求,并將FormData對象作為請求體。
使用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獲取到客戶端發(fā)送的表單數(shù)據(jù),在Node.js的Express框架中:
app.post('/api/upload', (req, res) => {
const formData = req.body; // 獲取客戶端發(fā)送的表單數(shù)據(jù)
// ...處理數(shù)據(jù)...
});
分享標(biāo)題:TypeScriptFormData詳解
瀏覽路徑:http://www.dlmjj.cn/article/cdghgeh.html


咨詢
建站咨詢
