1 var ajaxOptions = { 2 url: 'url', 3 method: 'GET', 4 async: true, 5 data: null, 6 dataType: 'text', 7 } 8 9 function ajax(protoOptions) { 10 var options = {}; 11 12 for(var i in ajaxOptions){ 13 options[i] = protoOptions[i] || ajaxOptions[i]; 14 } 15 16 17 return new Promise(function(resolve, reject){ 18 var xhr = new XMLHttpRequest(); 19 20 xhr.open(options.method, options.url, options.async); 21 22 xhr.onreadystatechange = function() { 23 if (this.readyState === 4 && this.status === 200) { 24 resolve(this.responseText, this); 25 } else { 26 var resJson = { 27 code: this.status, 28 response: this.response 29 } 30 reject(resJson, this) 31 } 32 } 33 34 xhr.send() 35 36 }) 37 }
用promise封装ajax
内容版权声明:除非注明,否则皆为本站原创文章。