1. FormData
对象的作用
- 模拟HTML表单,相当于将HTML表单映射成表单对象,自动将表单对象中的数据拼接成请求参数的格式。
- 异步上传二进制文件。
2. FormData
对象的使用
- 准备HTML表单
<form id="form">
<input type="text" name="username">
<input type="password" name="password">
<input type="button">
</form>
- 将HTML表单转化为
FormData
对象
var form = document.getElementById('form');
var formData = new FormData(form);
- 提交表单对象
xhr.send(formData);
注意:
(1)Formdata
对象不能用于get
请求,因为对象需要被传递到send
方法中,而get
请求方式的请求参数只能放在请求地址的后面。
(2)服务器端bodyParser
模块不能解析formData
对象表单数据,需要使用formidable
模块进行解析。
3. 简单实例
代码:
FormData.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!-- 创建普通的html表单 -->
<form id="form">
<input type="text" name="username">
<input type="password" name="password">
<input type="button" id="btn" value="提交">
</form>
<script>
// 获取按钮
var btn = document.getElementById('btn');
// 获取表单
var form = document.getElementById('form');
// 为按钮添加点击事件
btn.onclick = function() {
// 将普通的html表单转换为表单对象
var formData = new FormData(form);
// 创建ajax对象
var xhr = new XMLHttpRequest();
// 对ajax对象进行配置
xhr.open('post', 'http://localhost:3000/formData');
// 发送ajax请求
xhr.send(formData);
// 监听xhr对象下面的onload事件
xhr.onload = function() {
// 对象http状态码进行判断
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
</script>
</body>
</html>
app.js
:
// 引入express框架
const express = require('express');
// 路径处理模块
const path = require('path');
// 引入formidable模块
const formidable = require('formidable');
// 创建web服务器
const app = express();
// 静态资源访问服务功能
app.use(express.static(path.join(__dirname, 'public')));
app.post('/formData', (req, res) => {
// 创建formidable表单解析对象
const form = new formidable.IncomingForm();
// 解析客户端传递过来的FormData对象
// fields普通请求参数
// files关于文件上传的一些信息
form.parse(req, (err, fields, files) => {
res.send(fields);
});
});
// 监听端口
app.listen(3000);
// 控制台提示输出
console.log('服务器启动成功');
实现效果: