FormData 对象
- 可以模拟html表单 相当于将html 表单映射成表单对象 自动将表单对象中的数据拼接成请求参数的格式
- 异步上传二进制文件
准备html 表单
<form action="" id='form'>
<inpupt type='text' name='username'></inpupt>
<inpupt type='password' name='password'></inpupt>
<inpupt type='buttton'>
</form>
构造表单对象
var formData = new FormData(form)
提交表单对象
xhr.send(formData)
<script>
var form = document.getElementById('form')
var btn = document.getElementById('btn')
btn.onclick = function(){
// 创建表单对象
var formData = new FormData(form)
// 创建ajax 对象
var xhr = new XMLHttpRequest()
//对ajax 对象进行配置
xhr.open('post','http://localhost:3000/get')
xhr.send(formData)
xhr.onload = function(){
if(xhr.status == 200){
console.log(xhr.responseText)
}
}
}
</script>
get 方法
获取key 值
console.log(formData.get('username'))
set 方法
改变表单对象中的某个值
formData.set('key','value')
fomData.set('username','itcast')
delete 方法
删除表单对象中的属性值
.delete('key')
append 方法
.append('key','value')
FormData 二进制文件上传
二进制文件 图片 音频 视频
<input type='file' id='file'/>
<input type="file" id='file'>
<script>
// 获取文件选择控件
var file = document.getElementById('file')
// 为文件选择控件添加 onchange用户离开表单时触发 事件
// 在用户选择文件时触发
file.onchange = function(){
//创建空的表单对象
var formData = new FormData()
// 将用户选择的文件追加到formData 表单对象中
formData.append('attrName',this.files[0])
// 创建ajax 对象
var xhr = new XMLHttpRequest()
// 对ajax 对象进行配置
xhr.open('post','httt://locathost:300/upload')
// 发送ajax请求
xhr.send(formData)
// 监听服务端相应给客户段的数据
xhr.onload = function(){
// 如果服务器端返回的http为 200 请求成功
if(xhr.status == 200){
console.log(xhr.responseText)
}
}
}
</script>