let Ajax = function () { } Ajax.prototype = { constructor: Ajax, get: function (url) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = function() { // readyState == 4说明请求已完成 if (parseInt(xhr.readyState) === 4) { if (parseInt(xhr.status) === 200 || parseInt(xhr.status) === 304) { resolve(xhr.responseText); } else { reject(xhr); } } }; xhr.send(); }) }, post: function (url, data, contentType) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open("POST", url, true); // 添加http头,发送信息至服务器时内容编码类型 if (!contentType || contentType !== 'formdata' ) { !contentType && (contentType = 'application/x-www-form-urlencoded'); xhr.setRequestHeader('Content-Type', contentType); } xhr.onreadystatechange = function() { if (parseInt(xhr.readyState) === 4) { if (parseInt(xhr.status) === 200 || parseInt(xhr.status) === 304) { resolve(JSON.parse(xhr.responseText)); } else { reject(JSON.parse(xhr.responseText)); } } }; xhr.send(data); }) } } export default Ajax;