基础知识 https://developer.mozilla.org/en-US/docs/AJAX
upload(url,form,option)实现上传功能,
url:String表示上传的目标地址
form: HTMLFormElement 表单节点,待上传的文件
option:有两个部分,onload,是一个函数,上传成功回调,输入是服务器返回的json数据,onerror表示上传失败的信息。
调用方式
upload("ddd",form,{onload:function(){},onerror:function(){})
var upload = function(url,form,option){
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if (httpRequest.status === 200) {
option.onload(JSON.parse(xhr.responseText));
}
else {
option.onerror(xhr.status);
}
}
}
xhr.open("post",url,true);
xhr.send(serialize(form));
}
uploadPromise("url",form).then(function(){},function(){})要返回promise
function uploadPromise("url",form){
return new Promise(function(resolve,reject){
option = {
"onload":function(result){
resolve(result);
},
"onerror":function(error){
reject(error);
}
}
var req = upload("url",form,option);
});
}