function Ajax(config) { config = Object.assign({ url: '', type: 'GET', dataType: 'json', data: {} }, config); console.log(config); //1.建立ajax對象 var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP"); //2.設置回掉 xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status <= 300) { config.success && config.success(xhr.responseText, xhr.responseXML) } else { config.error && config.error(xhr.status) } } }; //3.鏈接和發送 if (config.type === 'GET' || config.type === 'get') { xhr.open('GET', config.url + '?' + formatParams(config.data), true); xhr.send(null); } else if (config.type === 'POST' || config.type === 'post') { xhr.open('POST', config.url, true); //設置請求頭以表單的形式提交 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(formatParams(config.data)); } function formatParams(data) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])); } arr.push("t=" + Math.random()); return arr.join("&") } }