1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| ~function(){ class ajaxClass { init(){ let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === 4 && /^[23]\d{2}$/.test(xhr.status)) { let response = xhr.responseText; try { switch(this.dataType.toUpperCase()) { case 'TEXT': case 'HTML': break; case 'JSON': response = JSON.parse(response); break; case 'XML': response = xhr.responseXML; break; } } catch (e) { console.log(e); } this.success(response); } } if (this.data !== null) { this.formatData(); if (this.isGET) { this.url += this.querySymbol() + this.data; this.data = null; } } this.isGET ? this.cacheFn() : null; xhr.open(this.method, this.url, this.async); xhr.send(this.data); } formatData() { if (Object.prototype.toString.call(this.data) === '[object Object]') { let obj = this.data, str = ``; for (let key in obj) { if (obj.hasOwnProperty(key)) { str += `${key}=${obj[key]}&`; } } this.data = str.replace(/&$/g,''); } } cacheFn(){ !this.cache ? this.url += `${this.querySymbol()}=${Math.random()}` : null; } querySymbol() { return this.url.indexOf('?') > -1 ? '&' : '?' } } window.ajax = function({ url=null, method='GET', type='GET', data=null, dataType='JSON', cache=true, async=true, success=null } = {}){ let _this = new ajaxClass(); ['url', 'method', 'data', 'dataType', 'cache', 'async', 'success'].forEach((item) => { if (item === 'method') { _this.method = type === null ? method : type; return; } if (item === 'success') { _this.success = typeof success === 'function' ? success : new Function(); return; } _this[item] = eval(item); }); _this.isGET = /^(GET|DELETE|HEAD)$/i.test(_this.method); _this.init(); return _this; } }();
|