原生封装的ajax函数
function Ajax(type, url, data, success, failed){ // 创建ajax对象 var xhr = null; if ( window.XMLHttpRequest ) {//非IE浏览器 xhr = new XMLHttpRequest(); } else {//IE浏览器 xhr = new ActiveXObject('Microsoft.XMLHTTP') } // 用于清除缓存 var random = Math.random(); if ( typeof data == 'object' ) { var str = ''; for(var key in data){ str += key+'='+data[key]+'&'; } data = str.replace(/&$/, ''); } if ( type.toUpperCase() == 'GET' ) { if( data ) { xhr.open('GET', url + '?' + data, true); } else { // xhr.open('GET', url + '?t=' + random, true); xhr.open('GET', url, true); } xhr.send(); } else if ( type.toUpperCase() == 'POST' ) { xhr.open('POST', url, true); // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(data); } // 处理返回数据 xhr.onreadystatechange = function() { if ( xhr.readyState == 4 ) { if ( xhr.status == 200 ) { success( xhr.responseText ); } else { if ( failed ) { failed( xhr.status ); } } } } }基于Promise封装的ajax函数
const getJSON = function( url ) { const promise = new Promise( function( resolve, reject ) { const handler = function() { if ( this.readyState !== 4 ) { return; } if ( this.status === 200 ) { resolve(this.response); } else { reject(new Error(this.statusText)); } }; const client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send(); }); return promise; };