formData:POST传参的另外的一种形式!
适合大段文字和文件类型;
演示:传少量的数据的时候,感受中文没有做转化!
// 1.注册提交事件
let form = document.querySelector("form");
form.onsubmit = function(e) {
e.preventDefault();
// 2.收集数据:使用formData传递数据:(下面是formData的语法)
// *********************************************方式1:不推荐
// let fd = new FormData();
// let bookname = document.getElementById('bookname')
// let author = document.getElementById('author')
// let publisher = document.getElementById('publisher')
// // 接口文档要求参数名,参数值
// fd.append('bookname', bookname.value)
// fd.append('author', author.value)
// fd.append('publisher', publisher.value);
// // fd不是{}对象!不能直接看收集的数据;
// // console.log(fd); // {bookname:"xxx"}
// // fd.forEach(function(val, key) {
// // console.log(val, key);
// // })
// *********************************************方式2:推荐
// let fd = new FormData(form); // 放入form原生DOM节点;
let fd = new FormData(this);
// 3.xhr实例化,
let xhr = new XMLHttpRequest();
// 设置请求方式路径
xhr.open("post", "http://www.liulongbin.top:3006/api/formdata");
xhr.send(fd); // 没有设置请求头!为什么?这个新的编码形式!
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
}