var BlueNet={ ParmsMaker:function(data){ var strtemp=''; for(var key in data[0]){ strtemp=strtemp+BlueNet.readJsonValue(data[0],key); } return strtemp.substring(0,strtemp.length-1); }, readJsonValue:function(data,key){ return key+"= '"+data[key]+"'&"; }, Post:function(url,data,success){ var xmlHttp = null; if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.open("POST", url, true); var datas=new Array(); datas.push(data); xmlHttp.send(this.ParmsMaker(datas)); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { success(xmlHttp.responseText); } } } }
使用方法如下:
var data={username:'fdfadfa', password:'fdsafds' } BlueNet.Post("你得地址",data,function(str){ //str是回调的字段 alert(str); });
又看到别人的文章,感觉自己还是太年轻了...建议直接看原版,以下是我的个人记录:
var myAjax = { // XMLHttpRequest IE7+, Firefox, Chrome, Opera, Safari ; ActiveXObject IE6, IE5 xhr: window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'), get: function (url, callback) { this.xhr.open('get', url); this.onreadystatechange(callback, this.xhr); this.xhr.send(null); }, post: function (url, data, callback) { this.xhr.open('post', url); this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); this.onreadystatechange(callback, this.xhr); this.xhr.send(data); }, onreadystatechange: function (func, _xhr) { _xhr.onreadystatechange = function () { if (_xhr.readyState == 4) { if (_xhr.status == 200) { func(_xhr.responseText); } } } } }
调用:
myAjax.post('AjaxHandler.ashx', 'func=GetServerTime' , function (data) { if (data) alert(data); } );