模拟写一个AJAX

2019-04-13 17:26发布

onreadystatechange 事件

注册 onreadystatechange 事件后,每当 readyState 属性改变时,就会调用 onreadystatechange 函数。 readyState:(存有 XMLHttpRequest 的状态。从 0 到 4 发生变化)
  • 0: 请求未初始化
  • 1: 服务器连接已建立
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已就绪

ES6写法: export default (type='GET', url='', data={}, async=true) => { return new Promise((resolve, reject) => { //定义一个promise type = type.toUpperCase(); let requestObj; if (window.XMLHttpRequest) { requestObj = new XMLHttpRequest(); } else { requestObj = new ActiveXObject; } if (type == 'GET') { let dataStr = ''; //数据拼接字符串 Object.keys(data).forEach(key => { dataStr += key + '=' + data[key] + '&'; }) dataStr = dataStr.substr(0, dataStr.lastIndexOf('&')); url = url + '?' + dataStr; requestObj.open(type, url, async); requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); requestObj.send(); }else if (type == 'POST') { requestObj.open(type, url, async); requestObj.setRequestHeader("Content-type", "application/json"); requestObj.send(JSON.stringify(data)); }else { reject('error type'); } requestObj.onreadystatechange = () => { if (requestObj.readyState == 4) { if (requestObj.status == 200) { let obj = requestObj.response if (typeof obj !== 'object') { obj = JSON.parse(obj); } resolve(obj); }else { reject(requestObj); } } } }) }