封装的Javascript异步请求方法
最近在看一些js基础知识,有些输出,这是其一。
var ajax = (function(){ var HTTP = {}; HTTP._factories = [ function(){ return new XMLHttpRequest()}, function(){ return new ActiveXObject('Microsoft.XMLHTTP')}, function(){ return new ActiveXObject('Msxml2.XMLHTTP')} ]; HTTP._factory = null; //保存可用的工厂函数 HTTP.newRequest = function(){ if(!!HTTP._factory) return HTTP._factory(); for(var i = 0; i < HTTP._factories.length; i++){ try{ var factory = HTTP._factories[i]; var request = factory(); if(!!request){ HTTP._factory = factory; return request; } }catch(e){ continue; } } HTTP._factory = function(){ throw new Error('XMLHttpRequest not supported'); } HTTP._factory(); }; /** * 将对象转换为get/post请求字符串 */ function obj2paramStr(obj) { if(!obj){ return ''; } var result = []; for(var key in obj){ result.push(key + '=' + encodeURIComponent(obj[key])); } return result.join('&'); } return function(config){ var _config = { type : 'GET', //请求方式 'POST','GET' url : '', //发送请求的地址 data : null, //发送到服务器的数据 async : false, //是否异步,默认异步 dataType : 'text', //预期服务器返回的数据类型 success : function(){}, //请求成功后的回调函数 jsonp : 'callback', //服务器端获取jsonp回调函数名的字段 jsonpCallback : 'callbackName' //jsonp回调函数名 } var request = HTTP.newRequest(); for(var key in _config){ if(typeof config[key] !== 'undefined'){ _config[key] = config[key]; } } if(typeof _config.data !== 'string'){ _config.data = obj2paramStr(_config.data) } if(_config.dataType == 'jsonp'){ var para = []; para.push(_config.jsonp + '=' + _config.jsonpCallback); if(_config.data !== ''){ para.push(_config.data); } para = para.join('&'); var script = document.createElement('script'); script.type = 'text/javascript'; script.src = _config.url + '?' + para; try{ document.body.appendChild(script); }catch(e){ console.error('The document is not loaded'); } return; } if(_config.type === 'GET'){ _config.url = _config.url + '?' + _config.data; } request.open(_config.type, _config.url, _config.async); request.onreadystatechange = function(){ if(request.readyState == 4 && request.status == 200){ switch(_config.dataType){ case 'text': _config.success(request.responseText); break; case 'xml': _config.success(request.responseXML.documentElement); break; case 'json': _config.success(eval('(' + request.responseText + ')')); break; } } }; if(_config.type === 'GET'){ request.send(null); }else{ request.setRequestHeader('Content-type', 'Application/x-www-form-urlencoded'); request.send(obj2paramStr(_config.data)); } }; })();
自己写的,虽然功能还不太强,有待进一步完善,不过基本需求也够用了。
参考书籍:《Javascript权威指南》