From 472f6badedaf90d43ecf25e74b5466c09448a438 Mon Sep 17 00:00:00 2001 From: hold-baby <535636391@qq.com> Date: Tue, 13 Feb 2018 14:29:56 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- example/static/ajax.js | 85 +++++++++++++++++++++++------------------ example/static/index.js | 55 ++++++++++++++------------ src/Ajax.js | 27 +++---------- src/Xhr.js | 8 +--- src/XhrFile.js | 58 ++++++++++++++++++++++------ 6 files changed, 134 insertions(+), 103 deletions(-) diff --git a/README.md b/README.md index 056f70e..952889a 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ uploader.onErrorItem = function(fileItem, res, status){ uploader.onProgressItem = function(fileItem, progress){ // 正在上传回调 } +uploader.upload() // 开始上传 ``` ## uploader opt @@ -84,6 +85,7 @@ uploader.onProgressItem = function(fileItem, progress){ var opt = { url : url, // 上传地址 isUploadClear : false, // 上传成功或失败后是否清除文件对象 - data : data // 上传附带参数 + data : data, // 上传附带参数 + autoUpload : false // 是否添加后自动上传 } ``` \ No newline at end of file diff --git a/example/static/ajax.js b/example/static/ajax.js index e417661..1134969 100644 --- a/example/static/ajax.js +++ b/example/static/ajax.js @@ -11,15 +11,9 @@ function xhrObj(type, opts, postData) { this.type = type; this.opts = opts; this.postData = postData; - this.catch = opts.catch; - this.mobileHandle = opts.mobileHandle; + this.catch = opts.catch || function () {}; this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); - if (!!this.mobileHandle && typeof this.mobileHandle == 'function') { - MOBLIE_CATCH.push(this.xmlHttp); - this.mobileHandle(); - } - this.xmlHttp.open(opts.method, opts.url, opts.async); this.xmlHttp.withCredentials = opts.withCredentials; for (var i in this.opts.headers) { @@ -100,10 +94,10 @@ function parseFileRes(evt) { /* xml上传文件 */ -function XhrFile(fileItem, dom) { +function XhrFile(opt, dom) { var _this = this; this.dom = dom; - this.fileItem = fileItem; + this.opt = opt; this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); this.xmlHttp.onload = uploadComplete; // 请求完成 @@ -123,13 +117,12 @@ function XhrFile(fileItem, dom) { _this.fileItem.isUploadding = true; }; - // 怎么延时确保自定义函数已绑定 - setTimeout(function () { - _this.onBeforeUploadItem(fileItem); - _this.xmlHttp.open("post", fileItem.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 - fileItem.formData.append("parm", JSON.stringify(fileItem.data)); // 文件对象添加额外参数 - _this.xmlHttp.send(fileItem.formData); //开始上传,发送form数据 - }, 100); + // 给input绑定change事件 + this.dom.onchange = function () { + if (_this.opt.autoUpload || false) { + _this.upload(); + } + }; //上传成功响应 function uploadComplete(evt) { @@ -189,9 +182,42 @@ function XhrFile(fileItem, dom) { } } +// 开始上传 +XhrFile.prototype.upload = function () { + if (!this.dom.value) return; + var _this = this; + + var fileObj = this.dom.files[0]; // js 获取文件对象 + var form = new FormData(); + form.append("file", fileObj); // 文件对象 + form.append("parm", JSON.stringify(this.opt.data)); // 文件对象添加额外参数 + + // 构建fileItem + var fileItem = { + formData: form, + url: this.opt.url || "", + data: this.opt.data || "", + addr: this.dom.value || "", + isUpload: false, + isCancel: false, + isUploadding: false, + isError: false, + isUploadClear: this.opt.isUploadClear || false, + autoUpload: this.opt.autoUpload || false + }; + + this.fileItem = fileItem; + + // 怎么延时确保自定义函数已绑定 + setTimeout(function () { + _this.onBeforeUploadItem(_this.fileItem); + _this.xmlHttp.open("post", _this.fileItem.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 + _this.xmlHttp.send(_this.fileItem.formData); //开始上传,发送form数据 + }, 20); +}; + // 取消上传 XhrFile.prototype.cancleUploadFile = function () { - console.log("cancleUploadFile"); _this.fileItem.isCancel = true; _this.fileItem.isUploadding = false; _this.fileItem.isUpload = false; @@ -201,12 +227,12 @@ XhrFile.prototype.cancleUploadFile = function () { // 清除文件 XhrFile.prototype.clearUploadFile = function () { if (this.fileItem.isUploadClear) { + // this.dom.outerHTML = this.dom.outerHTML; this.dom.value = ""; + this.dom.files[0] = null; } }; -window.MOBLIE_CATCH = []; //预留mobile拦截数组 - /* ajax构造函数 */ @@ -278,7 +304,7 @@ Ajax.prototype.config = function (opts) { }; // 请求方法集合 -var methods_1 = ['get', 'delete', 'head', 'options']; //不带data +var methods_1 = ['get', 'del', 'head', 'options']; //不带data var methods_2 = ['post', 'put', 'patch']; //带data for (var i in methods_1) { !function (methods_1, i) { @@ -312,24 +338,9 @@ for (var j in methods_2) { */ Ajax.prototype.uploader = function (id, opt) { var dom = document.getElementById(id); - var fileObj = dom.files[0]; // js 获取文件对象 - var form = new FormData(); - form.append("file", fileObj); // 文件对象 - - // 构建fileItem - var fileItem = { - formData: form, - url: opt.url || "", - data: opt.data || "", - addr: dom.value || "", - isUpload: false, - isCancel: false, - isUploadding: false, - isError: false, - isUploadClear: opt.isUploadClear || false - }; + if (dom.type !== "file") return; - return new XhrFile(fileItem, dom); + return new XhrFile(opt, dom); }; // 检验是否浏览器环境 diff --git a/example/static/index.js b/example/static/index.js index 9fdc661..efca53a 100644 --- a/example/static/index.js +++ b/example/static/index.js @@ -3,17 +3,21 @@ var addr = "http://127.0.0.1:10010" function on(id,fn){ var ele = document.getElementById(id); - ele.addEventListener("click",fn,false) -} + try{ + ele.addEventListener("click",fn,false) + }catch(e){ + ele.attachEvent("click",fn) + } +}; Ajax.catch = function(res){ console.log("catch") -} +}; Ajax.config({ headers : { 'Authorization' : "test" }, withCredentials : true, - baseUrl : addr, + baseUrl : addr }) on("ajax", function(){ @@ -34,7 +38,7 @@ on("get",function(){ }) }) on("delete",function(){ - Ajax.delete("/ajax/delete?u=delete").then(function(res){ + Ajax.del("/ajax/delete?u=delete").then(function(res){ console.log(res) }, function(res){ console.log(res) @@ -84,27 +88,28 @@ on("patch",function(){ console.log(res) }) }) -on("fileId",function(){ - var fileInput = document.getElementById("fileUpload") - var uploader = Ajax.uploader("fileUpload", { - url : addr + "/ajax/upload", - isUploadClear : true, - data : ["asdf","fsda"] - }) - uploader.onBeforeUploadItem = function(item){ - item.data = { - "123" : 321 - } - } - uploader.onSuccessItem = function(item, res, status){ - console.log(item); - } - uploader.onErrorItem = function(item, res, status){ - console.log(item) - } - uploader.onProgressItem = function(item, progress){ - console.log(item.isUpload) +var uploader = Ajax.uploader("fileUpload", { + url : addr + "/ajax/upload", + isUploadClear : true, + data : ["asdf","fsda"], + autoUpload : false +}) +uploader.onBeforeUploadItem = function(item){ + item.data = { + "123" : 321 } +} +uploader.onSuccessItem = function(item, res, status){ + console.log(item); +} +uploader.onErrorItem = function(item, res, status){ + console.log(item) +} +uploader.onProgressItem = function(item, progress){ + console.log(item.isUpload) +} +on("fileId",function(){ + uploader.upload() }) function showDes(str){ var des = document.getElementById("des"); diff --git a/src/Ajax.js b/src/Ajax.js index d2dbabd..7c18789 100644 --- a/src/Ajax.js +++ b/src/Ajax.js @@ -2,8 +2,6 @@ import {mergeHeaders, request_1, request_2} from './Common.js' import xhrObj from './Xhr.js' import XhrFile from './XhrFile.js' -window.MOBLIE_CATCH = []; //预留mobile拦截数组 - /* ajax构造函数 */ @@ -11,7 +9,7 @@ function Ajax(){ // 注册初始配置 this.opts = {}; this.opts.headers = { - 'Content-Type' : 'application/json;charset=utf-8', + 'Content-Type' : 'application/json;charset=utf-8' }; this.opts.method = 'POST'; this.opts.async = true; @@ -25,7 +23,7 @@ function Ajax(){ // 注册拦截函数 this.catch = function(){}; -} +}; /* 整合opt @@ -78,7 +76,7 @@ Ajax.prototype.config = function(opts){ // 请求方法集合 -var methods_1 = ['get', 'delete', 'head', 'options']; //不带data +var methods_1 = ['get', 'del', 'head', 'options']; //不带data var methods_2 = ['post', 'put', 'patch']; //带data for(var i in methods_1){ !function(methods_1, i){ @@ -112,24 +110,9 @@ for(var j in methods_2){ */ Ajax.prototype.uploader = function(id, opt){ var dom = document.getElementById(id); - var fileObj = dom.files[0]; // js 获取文件对象 - var form = new FormData(); - form.append("file", fileObj); // 文件对象 - - // 构建fileItem - var fileItem = { - formData : form, - url : opt.url || "", - data : opt.data || "", - addr : dom.value || "", - isUpload : false, - isCancel : false, - isUploadding : false, - isError : false, - isUploadClear : opt.isUploadClear || false - } + if(dom.type !== "file") return - return new XhrFile(fileItem, dom) + return new XhrFile(opt, dom) } export default Ajax \ No newline at end of file diff --git a/src/Xhr.js b/src/Xhr.js index c71da42..a851bc6 100644 --- a/src/Xhr.js +++ b/src/Xhr.js @@ -6,15 +6,9 @@ function xhrObj(type, opts, postData){ this.type = type; this.opts = opts; this.postData = postData; - this.catch = opts.catch; - this.mobileHandle = opts.mobileHandle + this.catch = opts.catch || function(){}; this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); - if(!!this.mobileHandle && typeof this.mobileHandle == 'function'){ - MOBLIE_CATCH.push(this.xmlHttp) - this.mobileHandle() - } - this.xmlHttp.open(opts.method, opts.url, opts.async); this.xmlHttp.withCredentials = opts.withCredentials; for(var i in this.opts.headers){ diff --git a/src/XhrFile.js b/src/XhrFile.js index 301b528..ae1b173 100644 --- a/src/XhrFile.js +++ b/src/XhrFile.js @@ -2,10 +2,10 @@ import {parseFileRes} from './Common.js' /* xml上传文件 */ -function XhrFile(fileItem, dom){ +function XhrFile(opt, dom){ var _this = this; this.dom = dom; - this.fileItem = fileItem; + this.opt = opt; this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); this.xmlHttp.onload = uploadComplete; // 请求完成 @@ -24,14 +24,14 @@ function XhrFile(fileItem, dom){ _this.fileItem.isUploadding = true; }; - // 怎么延时确保自定义函数已绑定 - setTimeout(function(){ - _this.onBeforeUploadItem(fileItem) - _this.xmlHttp.open("post", fileItem.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 - fileItem.formData.append("parm", JSON.stringify(fileItem.data)); // 文件对象添加额外参数 - _this.xmlHttp.send(fileItem.formData); //开始上传,发送form数据 - }, 100) - + // 给input绑定change事件 + this.dom.onchange = function(){ + if(_this.opt.autoUpload || false){ + _this.upload() + } + } + + //上传成功响应 function uploadComplete(evt) { //服务断接收完文件返回的结果 @@ -89,9 +89,43 @@ function XhrFile(fileItem, dom){ } } +// 开始上传 +XhrFile.prototype.upload = function(){ + if(!this.dom.value) return + var _this = this; + + var fileObj = this.dom.files[0]; // js 获取文件对象 + var form = new FormData(); + form.append("file", fileObj); // 文件对象 + form.append("parm", JSON.stringify(this.opt.data)); // 文件对象添加额外参数 + + // 构建fileItem + var fileItem = { + formData : form, + url : this.opt.url || "", + data : this.opt.data || "", + addr : this.dom.value || "", + isUpload : false, + isCancel : false, + isUploadding : false, + isError : false, + isUploadClear : this.opt.isUploadClear || false, + autoUpload : this.opt.autoUpload || false + } + + this.fileItem = fileItem; + + // 怎么延时确保自定义函数已绑定 + setTimeout(function(){ + _this.onBeforeUploadItem(_this.fileItem) + _this.xmlHttp.open("post", _this.fileItem.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 + _this.xmlHttp.send(_this.fileItem.formData); //开始上传,发送form数据 + }, 20) + +} + // 取消上传 XhrFile.prototype.cancleUploadFile = function(){ - console.log("cancleUploadFile") _this.fileItem.isCancel = true; _this.fileItem.isUploadding = false; _this.fileItem.isUpload = false; @@ -101,7 +135,9 @@ XhrFile.prototype.cancleUploadFile = function(){ // 清除文件 XhrFile.prototype.clearUploadFile = function(){ if(this.fileItem.isUploadClear){ + // this.dom.outerHTML = this.dom.outerHTML; this.dom.value = ""; + this.dom.files[0] = null; } } From 7e29d61a275c859f8d7e951194e4e69c1ba9c634 Mon Sep 17 00:00:00 2001 From: hold-baby <535636391@qq.com> Date: Wed, 17 Oct 2018 17:45:29 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=E8=AE=BE=E7=BD=AEheader?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dist/ajax.js | 115 +++++++++++++++++++++++++++++-------------- dist/ajax.min.js | 6 +-- dist/ajax.min.js.map | 2 +- src/Ajax.js | 2 + src/XhrFile.js | 7 +++ 5 files changed, 91 insertions(+), 41 deletions(-) diff --git a/dist/ajax.js b/dist/ajax.js index 57a8546..5d6ae61 100644 --- a/dist/ajax.js +++ b/dist/ajax.js @@ -11,15 +11,9 @@ function xhrObj(type, opts, postData) { this.type = type; this.opts = opts; this.postData = postData; - this.catch = opts.catch; - this.mobileHandle = opts.mobileHandle; + this.catch = opts.catch || function () {}; this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); - if (!!this.mobileHandle && typeof this.mobileHandle == 'function') { - MOBLIE_CATCH.push(this.xmlHttp); - this.mobileHandle(); - } - this.xmlHttp.open(opts.method, opts.url, opts.async); this.xmlHttp.withCredentials = opts.withCredentials; for (var i in this.opts.headers) { @@ -100,16 +94,16 @@ function parseFileRes(evt) { /* xml上传文件 */ -function XhrFile(form, opt, dom) { +function XhrFile(opt, dom) { var _this = this; - this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); this.dom = dom; + this.opt = opt; + + this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); this.xmlHttp.onload = uploadComplete; // 请求完成 this.xmlHttp.onerror = uploadFailed; // 请求失败 - this.xmlHttp.upload.onprogress = progressFunction; // 上传进度调用方法实现 - this.onSuccessItem = function () {}; this.onBeforeUploadItem = function () {}; this.onErrorItem = function () {}; @@ -120,29 +114,34 @@ function XhrFile(form, opt, dom) { //上传开始执行方法 ot = new Date().getTime(); //设置上传开始时间 oloaded = 0; //设置上传开始时,以上传的文件大小为0 + _this.fileItem.isUploadding = true; }; - setTimeout(function () { - _this.onBeforeUploadItem(form); - - _this.xmlHttp.open("post", opt.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 - _this.xmlHttp.send(form); //开始上传,发送form数据 - }, 100); + // 给input绑定change事件 + this.dom.onchange = function () { + if (_this.opt.autoUpload || false) { + _this.upload(); + } + }; //上传成功响应 function uploadComplete(evt) { //服务断接收完文件返回的结果 - console.log(evt); var res = parseFileRes(evt).res; var status = parseFileRes(evt).status; - _this.onSuccessItem(form, res, status); - // dom.value = ""; + _this.fileItem.isUpload = true; + _this.fileItem.isUploadding = false; + _this.onSuccessItem(_this.fileItem, res, status); + _this.clearUploadFile(); } //上传失败 function uploadFailed(evt) { var res = parseFileRes(evt).res; var status = parseFileRes(evt).status; - _this.onErrorItem(form, res, status); + _this.fileItem.isError = true; + _this.fileItem.isUploadding = false; + _this.onErrorItem(_this.fileItem, res, status); + _this.clearUploadFile(); } //上传进度实现方法,上传过程中会频繁调用该方法 @@ -155,7 +154,6 @@ function XhrFile(form, opt, dom) { progressBar.value = evt.loaded; progress.percent = Math.round(evt.loaded / evt.total * 100); } - var nt = new Date().getTime(); //获取当前时间 var pertime = (nt - ot) / 1000; //计算出上次调用该方法时到现在的时间差,单位为s ot = new Date().getTime(); //重新赋值时间,用于下次计算 @@ -180,22 +178,68 @@ function XhrFile(form, opt, dom) { progress.resttime = resttime; if (bspeed == 0) progress.bspeed = '上传已取消'; - _this.onProgressItem(form, progress); + _this.onProgressItem(_this.fileItem, progress); } } +// 开始上传 +XhrFile.prototype.upload = function () { + if (!this.dom.value) return; + var _this = this; + + var fileObj = this.dom.files[0]; // js 获取文件对象 + var form = new FormData(); + form.append("file", fileObj); // 文件对象 + form.append("parm", JSON.stringify(this.opt.data)); // 文件对象添加额外参数 + + // 构建fileItem + var fileItem = { + formData: form, + url: this.opt.url || "", + data: this.opt.data || "", + addr: this.dom.value || "", + isUpload: false, + isCancel: false, + isUploadding: false, + isError: false, + isUploadClear: this.opt.isUploadClear || false, + autoUpload: this.opt.autoUpload || false + }; + + this.fileItem = fileItem; + + // 怎么延时确保自定义函数已绑定 + setTimeout(function () { + _this.onBeforeUploadItem(_this.fileItem); + _this.xmlHttp.open("post", _this.fileItem.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 + + if (_this.opt.headers) { + for (var i in _this.opt.headers) { + _this.xmlHttp.setRequestHeader(i, _this.opt.headers[i]); + } + } + + _this.xmlHttp.send(_this.fileItem.formData); //开始上传,发送form数据 + }, 20); +}; + // 取消上传 XhrFile.prototype.cancleUploadFile = function () { - console.log("cancleUploadFile"); + _this.fileItem.isCancel = true; + _this.fileItem.isUploadding = false; + _this.fileItem.isUpload = false; this.xmlHttp.abort(); + this.clearUploadFile(); }; // 清除文件 XhrFile.prototype.clearUploadFile = function () { - this.dom.value = ""; + if (this.fileItem.isUploadClear) { + // this.dom.outerHTML = this.dom.outerHTML; + this.dom.value = ""; + this.dom.files[0] = null; + } }; -window.MOBLIE_CATCH = []; //预留mobile拦截数组 - /* ajax构造函数 */ @@ -216,9 +260,6 @@ function Ajax() { // 注册拦截函数 this.catch = function () {}; - - // 移动端请求句柄 - this.mobileHandle = null; } /* @@ -236,7 +277,6 @@ Ajax.prototype.creatOpts = function (opts) { _opts.method = opts.method && opts.method.toUpperCase(); _opts.catch = this.catch; - _opts.mobileHandle = this.mobileHandle; return _opts; }; @@ -253,6 +293,7 @@ Ajax.prototype.ajax = function (_opts) { return xml; } opts.url = this.opts.baseUrl + opts.url; + console.log(xmlHttp); return new xhrObj(opts, xmlHttp); }; @@ -270,7 +311,7 @@ Ajax.prototype.config = function (opts) { }; // 请求方法集合 -var methods_1 = ['get', 'delete', 'head', 'options']; //不带data +var methods_1 = ['get', 'del', 'head', 'options']; //不带data var methods_2 = ['post', 'put', 'patch']; //带data for (var i in methods_1) { !function (methods_1, i) { @@ -302,13 +343,13 @@ for (var j in methods_2) { /* 文件上传 */ -Ajax.prototype.uploader = function (dom, opt) { - var fileObj = dom.files[0]; // js 获取文件对象 +Ajax.prototype.uploader = function (id, opt) { + var dom = document.getElementById(id); + if (dom.type !== "file") return; - var form = new FormData(); - form.append("file", fileObj); // 文件对象 + opt.url = this.opts.baseUrl + opt.url; - return new XhrFile(form, opt, dom); + return new XhrFile(opt, dom); }; // 检验是否浏览器环境 diff --git a/dist/ajax.min.js b/dist/ajax.min.js index b89db3a..91ff907 100644 --- a/dist/ajax.min.js +++ b/dist/ajax.min.js @@ -1,9 +1,9 @@ /**! - * baby-ajax - v1.1.7 + * baby-ajax - v1.2.1 * One is only 5KB ajax library * - * Sat Feb 10 2018 17:09:26 GMT+0800 (中国标准时间) + * Wed Oct 17 2018 17:37:46 GMT+0800 (中国标准时间) * MIT (c) hold-baby */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.Ajax=e()}(this,function(){"use strict";function t(t,e,o){for(var s in this.type=t,this.opts=e,this.postData=o,this.catch=e.catch,this.mobileHandle=e.mobileHandle,this.xmlHttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),this.mobileHandle&&"function"==typeof this.mobileHandle&&(MOBLIE_CATCH.push(this.xmlHttp),this.mobileHandle()),this.xmlHttp.open(e.method,e.url,e.async),this.xmlHttp.withCredentials=e.withCredentials,this.opts.headers)this.xmlHttp.setRequestHeader(s,this.opts.headers[s]);return"methods_1"==t?this.xmlHttp.send(null):this.xmlHttp.send(this.postData),this}function e(t,e){for(var o in e)t[o]=e[o];return e}function o(t){try{var e=JSON.parse(t.responseText)}catch(o){e=t.responseText}return{status:t.status,data:e}}function s(e){return new t("methods_1",e)}function n(e){var o=e,s=[];for(var n in o.data)s.push(n+"="+o.data[n]);s.join("&");return new t("methods_2",o,JSON.stringify(o.data))}function i(t){return{res:JSON.parse(t.target.responseText),status:t.target.status}}function r(t,e,o){var s,n,r=this;this.xmlHttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),this.dom=o,this.xmlHttp.onload=function(e){var o=i(e).res,s=i(e).status;r.onSuccessItem(t,o,s)},this.xmlHttp.onerror=function(e){var o=i(e).res,s=i(e).status;r.onErrorItem(t,o,s)},this.xmlHttp.upload.onprogress=function(e){var o={},i={};e.lengthComputable&&(i.max=e.total,i.value=e.loaded,o.percent=Math.round(e.loaded/e.total*100));var a=((new Date).getTime()-s)/1e3;s=(new Date).getTime();var p=e.loaded-n;n=e.loaded;var h=p/a,l=h,u="b/s";h/1024>1&&(h/=1024,u="kb/s");h/1024>1&&(h/=1024,u="Mb/s");h=h.toFixed(1);var d=((e.total-e.loaded)/l).toFixed(1);o.speed=h+u,o.resttime=d,0==l&&(o.bspeed="上传已取消");r.onProgressItem(t,o)},this.onSuccessItem=function(){},this.onBeforeUploadItem=function(){},this.onErrorItem=function(){},this.onProgressItem=function(){},this.xmlHttp.upload.onloadstart=function(){s=(new Date).getTime(),n=0},setTimeout(function(){r.onBeforeUploadItem(t),r.xmlHttp.open("post",e.url,!0),r.xmlHttp.send(t)},100)}function a(){this.opts={},this.opts.headers={"Content-Type":"application/json;charset=utf-8"},this.opts.method="POST",this.opts.async=!0,this.opts.data=null,this.opts.url="",this.opts.baseUrl="",this.withCredentials=!1,this.catch=function(){},this.mobileHandle=null}t.prototype.then=function(t,e){var s=this;4==this.xmlHttp.readyState?(this.catch(o(this.xmlHttp)),this.xmlHttp.status>=200&&this.xmlHttp.status<300?t(o(this.xmlHttp)):e(o(this.xmlHttp))):setTimeout(function(){s.then(t,e)},20)},r.prototype.cancleUploadFile=function(){this.xmlHttp.abort()},r.prototype.clearUploadFile=function(){this.dom.value=""},window.MOBLIE_CATCH=[],a.prototype.creatOpts=function(t){var o=this.opts;for(var s in t)"headers"==s&&(o[s]=e(o[s],t[s])),o[s]=t[s];return o.method=t.method&&t.method.toUpperCase(),o.catch=this.catch,o.mobileHandle=this.mobileHandle,o},a.prototype.ajax=function(e){var o=this.creatOpts(e);return-1!==h.indexOf(o.method.toLowerCase())?n(o):-1!==p.indexOf(o.method.toLowerCase())?s(o):(o.url=this.opts.baseUrl+o.url,new t(o,xmlHttp))},a.prototype.config=function(t){for(var o in t)"headers"!=o?this.opts[o]=t[o]:t[o]=e(this.opts[o],t[o])};var p=["get","delete","head","options"],h=["post","put","patch"];for(var l in p)!function(t,e){a.prototype[t[e]]=function(o,n){var i=this.creatOpts(n||{});return i.method=t[e].toUpperCase(),i.url=this.opts.baseUrl+o,s(i)}}(p,l);for(var u in h)!function(t,e){a.prototype[t[e]]=function(o,s,i){return(i=this.creatOpts(i||{})).method=t[e].toUpperCase(),i.url=this.opts.baseUrl+o,i.data=s||{},n(i)}}(h,u);return a.prototype.uploader=function(t,e){var o=t.files[0],s=new FormData;return s.append("file",o),new r(s,e,t)},new a}); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.Ajax=e()}(this,function(){"use strict";function i(t,e,o){for(var s in this.type=t,this.opts=e,this.postData=o,this.catch=e.catch||function(){},this.xmlHttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),this.xmlHttp.open(e.method,e.url,e.async),this.xmlHttp.withCredentials=e.withCredentials,this.opts.headers)this.xmlHttp.setRequestHeader(s,this.opts.headers[s]);return"methods_1"==t?this.xmlHttp.send(null):this.xmlHttp.send(this.postData),this}function s(t,e){for(var o in e)t[o]=e[o];return e}function a(e){try{var o=JSON.parse(e.responseText)}catch(t){o=e.responseText}return{status:e.status,data:o}}function n(t){return new i("methods_1",t)}function r(t){var e=t,o=[];for(var s in e.data)o.push(s+"="+e.data[s]);o.join("&");return new i("methods_2",e,JSON.stringify(e.data))}function p(t){return{res:JSON.parse(t.target.responseText),status:t.target.status}}function l(t,e){var l,d,h=this;this.dom=e,this.opt=t,this.xmlHttp=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),this.xmlHttp.onload=function(t){var e=p(t).res,o=p(t).status;h.fileItem.isUpload=!0,h.fileItem.isUploadding=!1,h.onSuccessItem(h.fileItem,e,o),h.clearUploadFile()},this.xmlHttp.onerror=function(t){var e=p(t).res,o=p(t).status;h.fileItem.isError=!0,h.fileItem.isUploadding=!1,h.onErrorItem(h.fileItem,e,o),h.clearUploadFile()},this.xmlHttp.upload.onprogress=function(t){var e={},o={};t.lengthComputable&&(o.max=t.total,o.value=t.loaded,e.percent=Math.round(t.loaded/t.total*100));var s=((new Date).getTime()-l)/1e3;l=(new Date).getTime();var i=t.loaded-d;d=t.loaded;var a=i/s,n=a,r="b/s";1= 200 && this.xmlHttp.status < 300) {\n\t\t\tsuccess(parseResponse(this.xmlHttp));\n\t\t} else {\n\t\t\terror(parseResponse(this.xmlHttp));\n\t\t}\n\t} else {\n\t\tsetTimeout(function () {\n\t\t\t_this.then(success, error);\n\t\t}, 20);\n\t}\n};\n\n// 请求headers合并\nfunction mergeHeaders(headers, _headers) {\n\tfor (var i in _headers) {\n\t\theaders[i] = _headers[i];\n\t}\n\treturn _headers;\n}\n// 构建返回体\nfunction parseResponse(res) {\n\ttry {\n\t\tvar content = JSON.parse(res.responseText);\n\t} catch (e) {\n\t\tvar content = res.responseText;\n\t}\n\tvar data = {\n\t\tstatus: res.status,\n\t\tdata: content\n\t};\n\treturn data;\n}\n\nfunction request_1(_opts) {\n\treturn new xhrObj(\"methods_1\", _opts);\n}\n\nfunction request_2(_opts) {\n\tvar opts = _opts;\n\tvar params = [];\n\tfor (var key in opts.data) {\n\t\tparams.push(key + '=' + opts.data[key]);\n\t}\n\tvar postData = params.join('&');\n\tvar postData = JSON.stringify(opts.data);\n\treturn new xhrObj(\"methods_2\", opts, postData);\n}\n\n// 构建上传返回体\nfunction parseFileRes(evt) {\n\treturn {\n\t\tres: JSON.parse(evt.target.responseText),\n\t\tstatus: evt.target.status\n\t};\n}\n\n/*\r\n xml上传文件\r\n*/\nfunction XhrFile(form, opt, dom) {\n var _this = this;\n this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');\n this.dom = dom;\n this.xmlHttp.onload = uploadComplete; // 请求完成\n this.xmlHttp.onerror = uploadFailed; // 请求失败\n\n this.xmlHttp.upload.onprogress = progressFunction; // 上传进度调用方法实现\n\n\n this.onSuccessItem = function () {};\n this.onBeforeUploadItem = function () {};\n this.onErrorItem = function () {};\n this.onProgressItem = function () {};\n\n var ot, oloaded;\n this.xmlHttp.upload.onloadstart = function () {\n //上传开始执行方法\n ot = new Date().getTime(); //设置上传开始时间\n oloaded = 0; //设置上传开始时,以上传的文件大小为0\n };\n\n setTimeout(function () {\n _this.onBeforeUploadItem(form);\n\n _this.xmlHttp.open(\"post\", opt.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。\n _this.xmlHttp.send(form); //开始上传,发送form数据\n }, 100);\n\n //上传成功响应\n function uploadComplete(evt) {\n //服务断接收完文件返回的结果\n void 0;\n var res = parseFileRes(evt).res;\n var status = parseFileRes(evt).status;\n _this.onSuccessItem(form, res, status);\n // dom.value = \"\";\n }\n //上传失败\n function uploadFailed(evt) {\n var res = parseFileRes(evt).res;\n var status = parseFileRes(evt).status;\n _this.onErrorItem(form, res, status);\n }\n\n //上传进度实现方法,上传过程中会频繁调用该方法\n function progressFunction(evt) {\n var progress = {}; // 包含上传百分百 速度\n var progressBar = {};\n if (evt.lengthComputable) {\n //\n progressBar.max = evt.total;\n progressBar.value = evt.loaded;\n progress.percent = Math.round(evt.loaded / evt.total * 100);\n }\n\n var nt = new Date().getTime(); //获取当前时间\n var pertime = (nt - ot) / 1000; //计算出上次调用该方法时到现在的时间差,单位为s\n ot = new Date().getTime(); //重新赋值时间,用于下次计算\n var perload = evt.loaded - oloaded; //计算该分段上传的文件大小,单位b\n oloaded = evt.loaded; //重新赋值已上传文件大小,用以下次计算\n //上传速度计算\n var speed = perload / pertime; //单位b/s\n var bspeed = speed;\n var units = 'b/s'; //单位名称\n if (speed / 1024 > 1) {\n speed = speed / 1024;\n units = 'kb/s';\n }\n if (speed / 1024 > 1) {\n speed = speed / 1024;\n units = 'Mb/s';\n }\n speed = speed.toFixed(1);\n //剩余时间\n var resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);\n progress.speed = speed + units;\n progress.resttime = resttime;\n\n if (bspeed == 0) progress.bspeed = '上传已取消';\n _this.onProgressItem(form, progress);\n }\n}\n\n// 取消上传\nXhrFile.prototype.cancleUploadFile = function () {\n void 0;\n this.xmlHttp.abort();\n};\n// 清除文件\nXhrFile.prototype.clearUploadFile = function () {\n this.dom.value = \"\";\n};\n\nwindow.MOBLIE_CATCH = []; //预留mobile拦截数组\n\n/*\r\n ajax构造函数\r\n*/\nfunction Ajax() {\n\t// 注册初始配置\n\tthis.opts = {};\n\tthis.opts.headers = {\n\t\t'Content-Type': 'application/json;charset=utf-8'\n\t};\n\tthis.opts.method = 'POST';\n\tthis.opts.async = true;\n\tthis.opts.data = null;\n\tthis.opts.url = \"\";\n\tthis.opts.baseUrl = \"\";\n\n\t// 默认跨域不带cookie\n\tthis.withCredentials = false;\n\n\t// 注册拦截函数\n\tthis.catch = function () {};\n\n\t// 移动端请求句柄\n\tthis.mobileHandle = null;\n}\n\n/*\r\n 整合opt\r\n*/\nAjax.prototype.creatOpts = function (opts) {\n\tvar _opts = this.opts;\n\tfor (var i in opts) {\n\t\tif (i == \"headers\") {\n\t\t\t_opts[i] = mergeHeaders(_opts[i], opts[i]);\n\t\t}\n\t\t_opts[i] = opts[i];\n\t}\n\n\t_opts.method = opts.method && opts.method.toUpperCase();\n\n\t_opts.catch = this.catch;\n\t_opts.mobileHandle = this.mobileHandle;\n\treturn _opts;\n};\n\n/*\r\n ajax方法\r\n*/\nAjax.prototype.ajax = function (_opts) {\n\tvar opts = this.creatOpts(_opts);\n\tif (methods_2.indexOf(opts.method.toLowerCase()) !== -1) {\n\t\tvar xml = request_2(opts);\n\t\treturn xml;\n\t} else if (methods_1.indexOf(opts.method.toLowerCase()) !== -1) {\n\t\tvar xml = request_1(opts);\n\t\treturn xml;\n\t}\n\topts.url = this.opts.baseUrl + opts.url;\n\treturn new xhrObj(opts, xmlHttp);\n};\n\n/*\r\n 暴露一个配置方法\r\n*/\nAjax.prototype.config = function (opts) {\n\tfor (var i in opts) {\n\t\tif (i == \"headers\") {\n\t\t\topts[i] = mergeHeaders(this.opts[i], opts[i]);\n\t\t\tcontinue;\n\t\t}\n\t\tthis.opts[i] = opts[i];\n\t}\n};\n\n// 请求方法集合\nvar methods_1 = ['get', 'delete', 'head', 'options']; //不带data\nvar methods_2 = ['post', 'put', 'patch']; //带data\nfor (var i in methods_1) {\n\t!function (methods_1, i) {\n\t\tAjax.prototype[methods_1[i]] = function (url, _opts) {\n\n\t\t\tvar opts = this.creatOpts(_opts || {});\n\t\t\topts.method = methods_1[i].toUpperCase();\n\t\t\topts.url = this.opts.baseUrl + url;\n\n\t\t\tvar xml = request_1(opts);\n\t\t\treturn xml;\n\t\t};\n\t}(methods_1, i);\n}\nfor (var j in methods_2) {\n\t!function (methods_2, j) {\n\t\tAjax.prototype[methods_2[j]] = function (url, data, opts) {\n\t\t\topts = this.creatOpts(opts || {});\n\t\t\topts.method = methods_2[j].toUpperCase();\n\t\t\topts.url = this.opts.baseUrl + url;\n\t\t\topts.data = data || {};\n\n\t\t\tvar xml = request_2(opts);\n\t\t\treturn xml;\n\t\t};\n\t}(methods_2, j);\n}\n\n/*\r\n 文件上传\r\n*/\nAjax.prototype.uploader = function (dom, opt) {\n\tvar fileObj = dom.files[0]; // js 获取文件对象\n\n\tvar form = new FormData();\n\tform.append(\"file\", fileObj); // 文件对象\n\n\treturn new XhrFile(form, opt, dom);\n};\n\n// 检验是否浏览器环境\ntry {\n \n} catch (ex) {\n throw new Error('请在浏览器环境下运行');\n}\n\nvar index = new Ajax();\n\nreturn index;\n\n})));\n"]} \ No newline at end of file +{"version":3,"sources":["ajax.js"],"names":["global","factory","exports","module","define","amd","Ajax","this","xhrObj","type","opts","postData","i","catch","xmlHttp","window","XMLHttpRequest","ActiveXObject","open","method","url","async","withCredentials","headers","setRequestHeader","send","mergeHeaders","_headers","parseResponse","res","content","JSON","parse","responseText","e","status","data","request_1","_opts","request_2","params","key","push","join","stringify","parseFileRes","evt","target","XhrFile","opt","dom","ot","oloaded","_this","onload","fileItem","isUpload","isUploadding","onSuccessItem","clearUploadFile","onerror","isError","onErrorItem","upload","onprogress","progress","progressBar","lengthComputable","max","total","value","loaded","percent","Math","round","pertime","Date","getTime","perload","speed","bspeed","units","toFixed","resttime","onProgressItem","onBeforeUploadItem","onloadstart","onchange","autoUpload","Content-Type","baseUrl","prototype","then","success","error","readyState","setTimeout","fileObj","files","form","FormData","append","formData","addr","isCancel","isUploadClear","cancleUploadFile","abort","creatOpts","toUpperCase","ajax","methods_2","indexOf","toLowerCase","methods_1","config","j","uploader","id","document","getElementById"],"mappings":";;;;;;;CAAC,SAAUA,EAAQC,GACC,iBAAZC,SAA0C,oBAAXC,OAAyBA,OAAOD,QAAUD,IAC9D,mBAAXG,QAAyBA,OAAOC,IAAMD,OAAOH,GACnDD,EAAOM,KAAOL,IAHhB,CAIEM,KAAM,WAAe,aAKvB,SAASC,EAAOC,EAAMC,EAAMC,GAS3B,IAAK,IAAIC,KARTL,KAAKE,KAAOA,EACZF,KAAKG,KAAOA,EACZH,KAAKI,SAAWA,EAChBJ,KAAKM,MAAQH,EAAKG,OAAS,aAC3BN,KAAKO,QAAUC,OAAOC,eAAiB,IAAIA,eAAmB,IAAIC,cAAc,qBAEhFV,KAAKO,QAAQI,KAAKR,EAAKS,OAAQT,EAAKU,IAAKV,EAAKW,OAC9Cd,KAAKO,QAAQQ,gBAAkBZ,EAAKY,gBACtBf,KAAKG,KAAKa,QACvBhB,KAAKO,QAAQU,iBAAiBZ,EAAGL,KAAKG,KAAKa,QAAQX,IAQpD,MANY,aAARH,EACHF,KAAKO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K,IAAInG,KAAKsG,GACZ,SAAUA,EAAWtG,GACrBN,EAAKqF,UAAUuB,EAAUtG,IAAM,SAAUQ,EAAKkB,GAE7C,IAAI5B,EAAOH,KAAKqG,UAAUtE,GAAS,IAKnC,OAJA5B,EAAKS,OAAS+F,EAAUtG,GAAGiG,cAC3BnG,EAAKU,IAAMb,KAAKG,KAAKgF,QAAUtE,EAErBiB,EAAU3B,IAPrB,CAUCwG,EAAWtG,GAEd,IAAK,IAAIwG,KAAKL,GACZ,SAAUA,EAAWK,GACrB9G,EAAKqF,UAAUoB,EAAUK,IAAM,SAAUhG,EAAKgB,EAAM1B,GAOnD,OANAA,EAAOH,KAAKqG,UAAUlG,GAAQ,KACzBS,OAAS4F,EAAUK,GAAGP,cAC3BnG,EAAKU,IAAMb,KAAKG,KAAKgF,QAAUtE,EAC/BV,EAAK0B,KAAOA,GAAQ,GAEVG,EAAU7B,IAPrB,CAUCqG,EAAWK,GAwBd,OAlBA9G,EAAKqF,UAAU0B,SAAW,SAAUC,EAAIrE,GACvC,IAAIC,EAAMqE,SAASC,eAAeF,GAClC,GAAiB,SAAbpE,EAAIzC,KAIR,OAFAwC,EAAI7B,IAAMb,KAAKG,KAAKgF,QAAUzC,EAAI7B,IAE3B,IAAI4B,EAAQC,EAAKC,IAUb,IAAI5C","file":"ajax.min.js","sourcesContent":["(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.Ajax = factory());\n}(this, (function () { 'use strict';\n\n/*\r\n xml请求构造函数\r\n*/\nfunction xhrObj(type, opts, postData) {\n\tthis.type = type;\n\tthis.opts = opts;\n\tthis.postData = postData;\n\tthis.catch = opts.catch || function () {};\n\tthis.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');\n\n\tthis.xmlHttp.open(opts.method, opts.url, opts.async);\n\tthis.xmlHttp.withCredentials = opts.withCredentials;\n\tfor (var i in this.opts.headers) {\n\t\tthis.xmlHttp.setRequestHeader(i, this.opts.headers[i]);\n\t}\n\tif (type == \"methods_1\") {\n\t\tthis.xmlHttp.send(null);\n\t} else {\n\n\t\tthis.xmlHttp.send(this.postData);\n\t}\n\treturn this;\n}\n/*\r\n 请求回调\r\n*/\nxhrObj.prototype.then = function (success, error) {\n\tvar _this = this;\n\n\tif (this.xmlHttp.readyState == 4) {\n\t\tthis.catch(parseResponse(this.xmlHttp));\n\t\tif (this.xmlHttp.status >= 200 && this.xmlHttp.status < 300) {\n\t\t\tsuccess(parseResponse(this.xmlHttp));\n\t\t} else {\n\t\t\terror(parseResponse(this.xmlHttp));\n\t\t}\n\t} else {\n\t\tsetTimeout(function () {\n\t\t\t_this.then(success, error);\n\t\t}, 20);\n\t}\n};\n\n// 请求headers合并\nfunction mergeHeaders(headers, _headers) {\n\tfor (var i in _headers) {\n\t\theaders[i] = _headers[i];\n\t}\n\treturn _headers;\n}\n// 构建返回体\nfunction parseResponse(res) {\n\ttry {\n\t\tvar content = JSON.parse(res.responseText);\n\t} catch (e) {\n\t\tvar content = res.responseText;\n\t}\n\tvar data = {\n\t\tstatus: res.status,\n\t\tdata: content\n\t};\n\treturn data;\n}\n\nfunction request_1(_opts) {\n\treturn new xhrObj(\"methods_1\", _opts);\n}\n\nfunction request_2(_opts) {\n\tvar opts = _opts;\n\tvar params = [];\n\tfor (var key in opts.data) {\n\t\tparams.push(key + '=' + opts.data[key]);\n\t}\n\tvar postData = params.join('&');\n\tvar postData = JSON.stringify(opts.data);\n\treturn new xhrObj(\"methods_2\", opts, postData);\n}\n\n// 构建上传返回体\nfunction parseFileRes(evt) {\n\treturn {\n\t\tres: JSON.parse(evt.target.responseText),\n\t\tstatus: evt.target.status\n\t};\n}\n\n/*\r\n xml上传文件\r\n*/\nfunction XhrFile(opt, dom) {\n var _this = this;\n this.dom = dom;\n this.opt = opt;\n\n this.xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');\n this.xmlHttp.onload = uploadComplete; // 请求完成\n this.xmlHttp.onerror = uploadFailed; // 请求失败\n this.xmlHttp.upload.onprogress = progressFunction; // 上传进度调用方法实现\n\n this.onSuccessItem = function () {};\n this.onBeforeUploadItem = function () {};\n this.onErrorItem = function () {};\n this.onProgressItem = function () {};\n\n var ot, oloaded;\n this.xmlHttp.upload.onloadstart = function () {\n //上传开始执行方法\n ot = new Date().getTime(); //设置上传开始时间\n oloaded = 0; //设置上传开始时,以上传的文件大小为0\n _this.fileItem.isUploadding = true;\n };\n\n // 给input绑定change事件\n this.dom.onchange = function () {\n if (_this.opt.autoUpload || false) {\n _this.upload();\n }\n };\n\n //上传成功响应\n function uploadComplete(evt) {\n //服务断接收完文件返回的结果\n var res = parseFileRes(evt).res;\n var status = parseFileRes(evt).status;\n _this.fileItem.isUpload = true;\n _this.fileItem.isUploadding = false;\n _this.onSuccessItem(_this.fileItem, res, status);\n _this.clearUploadFile();\n }\n //上传失败\n function uploadFailed(evt) {\n var res = parseFileRes(evt).res;\n var status = parseFileRes(evt).status;\n _this.fileItem.isError = true;\n _this.fileItem.isUploadding = false;\n _this.onErrorItem(_this.fileItem, res, status);\n _this.clearUploadFile();\n }\n\n //上传进度实现方法,上传过程中会频繁调用该方法\n function progressFunction(evt) {\n var progress = {}; // 包含上传百分百 速度\n var progressBar = {};\n if (evt.lengthComputable) {\n //\n progressBar.max = evt.total;\n progressBar.value = evt.loaded;\n progress.percent = Math.round(evt.loaded / evt.total * 100);\n }\n var nt = new Date().getTime(); //获取当前时间\n var pertime = (nt - ot) / 1000; //计算出上次调用该方法时到现在的时间差,单位为s\n ot = new Date().getTime(); //重新赋值时间,用于下次计算\n var perload = evt.loaded - oloaded; //计算该分段上传的文件大小,单位b\n oloaded = evt.loaded; //重新赋值已上传文件大小,用以下次计算\n //上传速度计算\n var speed = perload / pertime; //单位b/s\n var bspeed = speed;\n var units = 'b/s'; //单位名称\n if (speed / 1024 > 1) {\n speed = speed / 1024;\n units = 'kb/s';\n }\n if (speed / 1024 > 1) {\n speed = speed / 1024;\n units = 'Mb/s';\n }\n speed = speed.toFixed(1);\n //剩余时间\n var resttime = ((evt.total - evt.loaded) / bspeed).toFixed(1);\n progress.speed = speed + units;\n progress.resttime = resttime;\n\n if (bspeed == 0) progress.bspeed = '上传已取消';\n _this.onProgressItem(_this.fileItem, progress);\n }\n}\n\n// 开始上传\nXhrFile.prototype.upload = function () {\n if (!this.dom.value) return;\n var _this = this;\n\n var fileObj = this.dom.files[0]; // js 获取文件对象\n var form = new FormData();\n form.append(\"file\", fileObj); // 文件对象\n form.append(\"parm\", JSON.stringify(this.opt.data)); // 文件对象添加额外参数\n\n // 构建fileItem\n var fileItem = {\n formData: form,\n url: this.opt.url || \"\",\n data: this.opt.data || \"\",\n addr: this.dom.value || \"\",\n isUpload: false,\n isCancel: false,\n isUploadding: false,\n isError: false,\n isUploadClear: this.opt.isUploadClear || false,\n autoUpload: this.opt.autoUpload || false\n };\n\n this.fileItem = fileItem;\n\n // 怎么延时确保自定义函数已绑定\n setTimeout(function () {\n _this.onBeforeUploadItem(_this.fileItem);\n _this.xmlHttp.open(\"post\", _this.fileItem.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。\n\n if (_this.opt.headers) {\n for (var i in _this.opt.headers) {\n _this.xmlHttp.setRequestHeader(i, _this.opt.headers[i]);\n }\n }\n\n _this.xmlHttp.send(_this.fileItem.formData); //开始上传,发送form数据\n }, 20);\n};\n\n// 取消上传\nXhrFile.prototype.cancleUploadFile = function () {\n _this.fileItem.isCancel = true;\n _this.fileItem.isUploadding = false;\n _this.fileItem.isUpload = false;\n this.xmlHttp.abort();\n this.clearUploadFile();\n};\n// 清除文件\nXhrFile.prototype.clearUploadFile = function () {\n if (this.fileItem.isUploadClear) {\n // this.dom.outerHTML = this.dom.outerHTML;\n this.dom.value = \"\";\n this.dom.files[0] = null;\n }\n};\n\n/*\r\n ajax构造函数\r\n*/\nfunction Ajax() {\n\t// 注册初始配置\n\tthis.opts = {};\n\tthis.opts.headers = {\n\t\t'Content-Type': 'application/json;charset=utf-8'\n\t};\n\tthis.opts.method = 'POST';\n\tthis.opts.async = true;\n\tthis.opts.data = null;\n\tthis.opts.url = \"\";\n\tthis.opts.baseUrl = \"\";\n\n\t// 默认跨域不带cookie\n\tthis.withCredentials = false;\n\n\t// 注册拦截函数\n\tthis.catch = function () {};\n}\n\n/*\r\n 整合opt\r\n*/\nAjax.prototype.creatOpts = function (opts) {\n\tvar _opts = this.opts;\n\tfor (var i in opts) {\n\t\tif (i == \"headers\") {\n\t\t\t_opts[i] = mergeHeaders(_opts[i], opts[i]);\n\t\t}\n\t\t_opts[i] = opts[i];\n\t}\n\n\t_opts.method = opts.method && opts.method.toUpperCase();\n\n\t_opts.catch = this.catch;\n\treturn _opts;\n};\n\n/*\r\n ajax方法\r\n*/\nAjax.prototype.ajax = function (_opts) {\n\tvar opts = this.creatOpts(_opts);\n\tif (methods_2.indexOf(opts.method.toLowerCase()) !== -1) {\n\t\tvar xml = request_2(opts);\n\t\treturn xml;\n\t} else if (methods_1.indexOf(opts.method.toLowerCase()) !== -1) {\n\t\tvar xml = request_1(opts);\n\t\treturn xml;\n\t}\n\topts.url = this.opts.baseUrl + opts.url;\n\tvoid 0;\n\treturn new xhrObj(opts, xmlHttp);\n};\n\n/*\r\n 暴露一个配置方法\r\n*/\nAjax.prototype.config = function (opts) {\n\tfor (var i in opts) {\n\t\tif (i == \"headers\") {\n\t\t\topts[i] = mergeHeaders(this.opts[i], opts[i]);\n\t\t\tcontinue;\n\t\t}\n\t\tthis.opts[i] = opts[i];\n\t}\n};\n\n// 请求方法集合\nvar methods_1 = ['get', 'del', 'head', 'options']; //不带data\nvar methods_2 = ['post', 'put', 'patch']; //带data\nfor (var i in methods_1) {\n\t!function (methods_1, i) {\n\t\tAjax.prototype[methods_1[i]] = function (url, _opts) {\n\n\t\t\tvar opts = this.creatOpts(_opts || {});\n\t\t\topts.method = methods_1[i].toUpperCase();\n\t\t\topts.url = this.opts.baseUrl + url;\n\n\t\t\tvar xml = request_1(opts);\n\t\t\treturn xml;\n\t\t};\n\t}(methods_1, i);\n}\nfor (var j in methods_2) {\n\t!function (methods_2, j) {\n\t\tAjax.prototype[methods_2[j]] = function (url, data, opts) {\n\t\t\topts = this.creatOpts(opts || {});\n\t\t\topts.method = methods_2[j].toUpperCase();\n\t\t\topts.url = this.opts.baseUrl + url;\n\t\t\topts.data = data || {};\n\n\t\t\tvar xml = request_2(opts);\n\t\t\treturn xml;\n\t\t};\n\t}(methods_2, j);\n}\n\n/*\r\n 文件上传\r\n*/\nAjax.prototype.uploader = function (id, opt) {\n\tvar dom = document.getElementById(id);\n\tif (dom.type !== \"file\") return;\n\n\topt.url = this.opts.baseUrl + opt.url;\n\n\treturn new XhrFile(opt, dom);\n};\n\n// 检验是否浏览器环境\ntry {\n \n} catch (ex) {\n throw new Error('请在浏览器环境下运行');\n}\n\nvar index = new Ajax();\n\nreturn index;\n\n})));\n"]} \ No newline at end of file diff --git a/src/Ajax.js b/src/Ajax.js index 7c18789..f04c2dd 100644 --- a/src/Ajax.js +++ b/src/Ajax.js @@ -112,6 +112,8 @@ Ajax.prototype.uploader = function(id, opt){ var dom = document.getElementById(id); if(dom.type !== "file") return + opt.url = this.opts.baseUrl + opt.url; + return new XhrFile(opt, dom) } diff --git a/src/XhrFile.js b/src/XhrFile.js index ae1b173..5c9f486 100644 --- a/src/XhrFile.js +++ b/src/XhrFile.js @@ -119,6 +119,13 @@ XhrFile.prototype.upload = function(){ setTimeout(function(){ _this.onBeforeUploadItem(_this.fileItem) _this.xmlHttp.open("post", _this.fileItem.url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。 + + if(_this.opt.headers){ + for(var i in _this.opt.headers){ + _this.xmlHttp.setRequestHeader(i, _this.opt.headers[i]); + } + } + _this.xmlHttp.send(_this.fileItem.formData); //开始上传,发送form数据 }, 20) From 2e2cc56944e1b37a3a524aa5020b442cd3c7d8d5 Mon Sep 17 00:00:00 2001 From: hold-baby <535636391@qq.com> Date: Wed, 17 Oct 2018 17:45:59 +0800 Subject: [PATCH 3/3] v1.2.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8eea952..8637213 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "baby-ajax", - "version": "1.2.1", + "version": "1.2.2", "description": "One is only 5KB ajax library", "main": "dist/ajax.min.js", "scripts": {