原生js实现ajax发送文件
传入一个对象,类似于jquery的$.ajax(对象)的用法
window.ajaxFiles=(obj)=>{
//url,可加可不加'/'
let url=obj.url.startsWith('/')?obj.url:'/'+obj.url;
//发送的对象
let data=obj.data||{};
//成功的回调函数
let func=obj.func;
//类型检测
if(typeof url !=='string')
throw new Error('url must be string !');
if(typeof data !=='object')
throw new Error('data must be one object');
if(typeof func !=='function')
throw new Error('func must be one function!');
let xml=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHttp");
if(!xml){
alert('浏览器无法创建XMLHttpRequest和ActiveXObject对象');
}
xml.onreadystatechange=()=>{
if(xml.readyState===4&&xml.status===200){
if(xml.responseText instanceof String){
func(xml.responseText);
}
func(JSON.parse(xml.responseText));
}
};
xml.open('post','/'+url,true);
xml.send(parseData(data));
//将普通对象转换为formData
function parseData(obj) {
let form=new FormData();
for(let i in obj){
form.append(i,obj[i]);
}
return form;
}
};
使用实例
ajaxFiles({
url:'register',
data:{
name:'lfb',
//getNode是我封装的获取节点的方法,可以使用最基本的获取节点的方法
//获取input file框的文件
file:getNode('#file').files[0]
},
func:(res)=>{
console.log(res);
}
})
注意!!!要在服务端设置允许跨域!
作者寄语
我亲测有效,如发现bug,请留言,万分感谢!