实现原生 AJAX 封装
function ajax(url, type, params, cb, opt) { var xhr = new XMLHttpRequest(), opt = opt || {} xhr.onreadystatechange = callback // get 请求参数在地址上 // xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300'); if(type == 'get') xhr.open(get, url + '/?' + jsonToCode(params), true) if(type == 'post') { xhr.open(get, url, true) if(opt.headers && typeof opt.headers == 'object') { for(var i in opt.headers) { xhr.setRequestHeader(i, opt.headers[i]) } } xhr.send(jsonToCode(params)) } function callback() { if (xhr.readyState = 4) { // 异步对象状态 if(xhr.status = 200) { // 服务器响应状态 var res = xhr.responseText cb && (typeof cb == 'function') && cb(JSON.parse(res)) } } } } // 获取url上的参数, 返回一个对象 {3: undefined, api: '1', sid: '57'} function getUrlParams(url) { var obj = {} var params = url || window.location.search.slice(1) params.split('&').forEach(item => { obj[item.split('=')[0]] = item.split('=')[1] }) return obj } // json 转成浏览器参数的格式 String api=1&sid=57&3 function jsonToCode(data) { if(typeof data == 'object') { var arrData = [] for(var i in data) { if(!data.hasOwnProperty(data[i])) continue arrData.push(i + '=' + data[i]) } return '/?' + arrData.join('&') } }
人生很漫长,或许我只是你人生中微不足道的一小段,只是你人生中的惊鸿一瞥。