之前一直用jquery,项目中遇到ajax也是用jq自带的$.ajax来实现,最近公司要求项目去jquery化,新项目都用vue,感觉脱离了操作dom的苦海,不过相比jquery的大而全,很多东西需要自己写,比如ajax,下面自己用原生的封装了一个,支持json和jsonp,直接上代码:
function Ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.url = options.url || location.href; options.dataType = options.dataType || 'json'; options.async = options.async || true; options.timeout = options.timeout || 30000;//超时处理,默认30s options.contentType = options.contentType || "application/x-www-form-urlencoded;charset=UTF-8"; //可选:application/json application/x-www-form-urlencoded options.heads = options.heads || {}; options.data = options.data || {}; var timeoutFlag = null; var params =options.data; var xhr; var that = this; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP') } xhr.onreadystatechange = function () { if (options.dataType === 'json') { // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。 if (xhr.readyState == 4) { window.clearTimeout(options.timeoutFlag); var status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText, xhr.responseXML); } else { options.fail && options.fail(status); } } } else { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { window.clearTimeout(options.timeoutFlag); var oScript = document.createElement('script'); document.body.appendChild(oScript); var callbackname = 'ajaxCallBack' oScript.src = options.url + "?" + params + '&callback=' + callbackname; window['ajaxCallBack'] = function (data) { options.success(data); document.body.removeChild(oScript); }; } } }; if (options.type == 'GET') { params = getParams(params); xhr.open("GET", options.url + '?' + params, options.async); setHeader(); xhr.send(null) } else if (options.type == 'POST') { xhr.open('POST', options.url, options.async); setHeader(); xhr.send(getParams(params)); } var timeoutFlag = options.timeoutFlag; timeoutFlag=window.setTimeout(function () { window.clearTimeout(timeoutFlag); xhr.abort(); alert("ajax请求超时"); },options.timeout); function setHeader() { xhr.setRequestHeader("Content-Type", options.contentType); for (var head in options.heads) { xhr.setRequestHeader(head, options.heads[head]); } xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } //json转为键值对,支持多级。 function getParams(data,parentKey) { var arr = []; for (var param in data) { var paramName = param; if (parentKey != undefined) { paramName = parentKey + "[" + param+"]"; } if (typeof (data[param])=="object") { arr.push(getParams(data[param], paramName)); } else { arr.push(encodeURIComponent(paramName) + '=' + encodeURIComponent(data[param])); } } return arr.join('&'); } }
最近工作忙,很少写文章了,欢迎大家转发和关注,