从08年2到12年,对XNILHttpRequest进行了升级扩展,新增了很多新属性和方法,这就是xhr2.0版本
xhr2.0 中不仅仅增加了属性和方法,还提出了很多新的构想,以及常见问题的解决方案,比如FormData/CORS等*/
document.querySelector('form').onsubmit = function (e) {
e.preventDefault();
// 收集表单数据
let fd = new FormData(this); // jquery使用 $(this).serialize()收集表单数据
// 追加数据 不会把age覆盖
fd.append('age', 20);
fd.append('age', 30);
// 修改数据 会把原来数据干掉 比如原来有两个age 设置以后就成一个age
fd.set('username', 'laotang');
// 获取数据
// fd.get('age') //获取一个age
// fd.getAll('age') //获取所有age
// console.log(fd); // 直接打印对象,是看不到数据的 , 必须通过forEach遍历fd对象,才能看到这个对象中的数据
fd.forEach((item, index) => {
item是值 index是name名
console.log(item,index);
});
----------------------------------------------------------
// 原生xhr发送ajax
let xhr = new XMLHttpRequest();
xhr.onload = function () {
let res = (xhr.responseText);
console.log(res);
}
xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata');
FormData当请求体的时候 不需要手动指定Content-Type,浏览器会自动添加
xhr.send(fd);
// 使用jquery发送ajax的写法
$.ajax({
type: 'POST',
url: 'http://www.liulongbin.top:3006/api/formdata',
data: fd,
processData: false, // 不需要把 fd 对象转成查询字符串。
contentType: false, // 意思是不要使用默认的contentType()
success: function (res) {
console.log(res);
}
});
}
FormData可以收集文件域的值,而serialize不能。也就是说,如果有文件上传,必须使用FormData。