ajax请求封装
var xmlHttp; var ajaxRequest = function (params) { xmlHttp ={}; this.url = params.url; this.method = params.method; this.dataType = params.dataType; this.formData = params.formData;//string 仅用于post this.init = function(){ if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码 xmlHttp=new XMLHttpRequest(); } else { // IE6, IE5 浏览器执行代码 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.onreadystatechange = function() { //这里总是无法调用this.xmlHttp 干脆改成全局变量了 if (xmlHttp.readyState==4 && xmlHttp.status==200) { document.getElementById("myDiv").innerHTML=xmlHttp.responseText; } } xmlHttp.open(this.method, this.url, true); xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //xmlHttp.setRequestHeader('Content-length', this.formData.length); //xmlHttp.setRequestHeader("Referer", "http://www.baidu.com"); //xmlHttp.setRequestHeader('Connection', 'close'); return true; }; this.send = function(){ if(this.init()){ console.log(this.formData); xmlHttp.send(this.formData); } }; }; var FormData = function(){ this.data = '' ; this.append = function(key,val){ if(typeof key == 'string' && typeof val == 'string') this.data += key + '=' + val; } this.batchAppend = function(a){ if(typeof a == 'array' || typeof a == 'object') { for(var i in a) { if(typeof a[i] == 'string') { this.data += i + '=' + a[i] + '&'; } } this.data = this.data.substr(0,this.data.length-1); } } return this.data; } var data = new FormData(); data.append('user', 'sachin'); //data.batchAppend({'fdf':'1313','8':'5454'}); var params = { url : 'http://localhost/test/test.php?b=234234', method : 'GET', dataType: 'text', formData : data }; //console.log(data); var request = new ajaxRequest(params); request.send();