简单模仿 jQuery 中 $.ajax() 方法
(function(){ // Ajax 选项 var options = { type: "GET", //提交方式 url: "", //路径 params: {}, //请求参数 dataType: "text", //内容类型 success: function(){}, //回调函数 error: function(){} }; //获取 XMLHTTPRequest 对象 var createRequest = function(){ var xmlhttp; if(xmlhttp.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } if(xmlhttp.overrideMimeType){ xmlhttp.overrideMimeType('text/xml'); //修改 MIME 类型 } return xmlhttp; }, // 设定 Ajax 选项 var setOptions = function(newOptions){ for(var prop in newOptions){ if(newOptions.hasOwnProperty(prop)){ this.option[prop] = newOptions[prop]; } } }, //格式化参数列表 var formatParameters = function(){ var paramsArr = []; var params = this.options.params; for(var prop in params){ if(params.hasOwnProperty(prop)){ paramsArr.push(prop + "=" + encodeURIComponent(params[prop])); } } return paramsArr.join('&'); }, //预处理并调用相应函数 var readystatechange = function(xmlhttp){ var returnValue; if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ switch(this.options.dataType){ case 'xml': returnValue = ; break; case'json': returnVaue = xmlhttp.responseText; if(returnValue){ returnValue = ("(" + returnValue + ")"); } break; default: returnVaue = xmlhttp.responseText; break; } if(returnValue){ this.options.success(returnValue); } else{ this.options.success(); } } else{ this.options.error(); } }, //发送请求,也就是$.ajax()函数 var request = function(options){ // var ajaxObj = this; var xmlhttp = this.createRequest(); this.setOptions(options); xmlhttp.onreadystatechange = this.readystatechange.bind(null, xmlhttp); var formatParams = this.formatParameters(); var type = this.options.type; var url = this.options.url; if("GET" === type.toUpperCase()){ url += "?" + formatParameters; } xmlhttp.open(type, url, true); if("GET" === type.toUpperCase()){ xmlhttp.send(); } else if("POST" === type.toUpperCase()){ xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlhttp.send(formatParameters); } } window.$.ajax = request; //暴露方法到闭包外面去 })();Tags:ajax xml 异步 json jsonp