基礎(chǔ)知識(shí) https://developer.mozilla.org/en-US/docs/AJAX
upload(url,form,option)實(shí)現(xiàn)上傳功能,
url:String表示上傳的目標(biāo)地址
form: HTMLFormElement 表單節(jié)點(diǎn),待上傳的文件
option:有兩個(gè)部分撬腾,onload,是一個(gè)函數(shù)钓试,上傳成功回調(diào)装黑,輸入是服務(wù)器返回的json數(shù)據(jù),onerror表示上傳失敗的信息弓熏。
調(diào)用方式
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);
});
}