通过ES6实现的Ajax类
个人学习用途而已,仅供参考。
1 class Ajax { 2 constructor(xhr) { 3 xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 4 this.xhr = xhr; 5 } 6 7 send(method, url, async, callback, data) { 8 let xhr = this.xhr; 9 10 xhr.onreadystatechange = () => { 11 // readyState: 0: init, 1: connect has set up, 2: recive request, 3: request.. , 4: request end, send response 12 if (xhr.readyState === 4 && xhr.status === 200) { 13 // status: 200: OK, 404: Not Found Page 14 callback(xhr.responseText); 15 } 16 }; 17 18 xhr.open(method, url, async); 19 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 20 xhr.send(data); 21 } 22 }
Promise增强版:
1 class Ajax { 2 constructor(xhr) { 3 xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 4 this.xhr = xhr; 5 } 6 7 send(options) { 8 9 let xhr = this.xhr; 10 11 let opt = { 12 type: options.type || 'get', 13 url: options.url || '', 14 async: options.async || true, 15 dataType: options.dataType || 'json', 16 questring: options.questring || '' 17 }; 18 19 return new Promise((resolve, reject) => { 20 21 xhr.open(opt.type, opt.url, opt.async); 22 23 xhr.onreadystatechange = () => { 24 // readyState: 0: init, 1: connect has set up, 2: recive request, 3: request.. , 4: request end, send response 25 if (xhr.readyState === 4) { 26 if (xhr.status === 200) { 27 // status: 200: OK, 404: Not Found Page 28 if (opt.dataType === 'json') { 29 const data = JSON.parse(xhr.responseText); 30 resolve(data); 31 } 32 } else { 33 reject(new Error(xhr.status || 'Server is fail.')); 34 } 35 } 36 }; 37 38 xhr.onerror = () => { 39 reject(new Error(xhr.status || 'Server is fail.')); 40 } 41 42 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 43 xhr.send(opt.questring); 44 45 }); 46 } 47 }
学习是一条令人时而喜极若狂、时而郁郁寡欢的道路。