var Ajax = (function(){
//加载json
if(typeof JSON == "undefined"){
var script = document.createElement("script");
script.type = "text/javascript";
//替换成静态地址
script.src="json2.js";
document.getElementsByTagName("head")[0].appendChild(script);
}
//查找功能函数
function findFrom(){
var returnValue;
for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) { }
}
return returnValue;
}
//xml http request取得ajax的请求工具
var httpRequest = function(){
var returnValue = false;
return findFrom(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
)||false;
}();
var proto = {
method:null,
dataType:"JSON",
post:function(params){
this.method = "POST";
this._send(params);
},
get:function(params){
this.method = "GET";
this._send(params);
},
_send:function(data){
var strData = this._serialize(data);
if(this.method == "GET"){
this.url=this.url+"?"+strData;
}
this.HttpRequest.open(this.method,this.url,this.async);
//监听事件
var r = this.HttpRequest,self = this;
r.onreadystatechange=function(){
console.log(r.readyState);
if (r.readyState==4 && r.status==200){
try{
var data = null;
if(this.dataType.toUpperCase() == "JSON"){
data = eval(r.responseText);
}else{
data = r.responseText;
}
}catch(e){
'error';
}
self.onSuccess(data);
}
}
self.onLoading();
if(this.method == "POST"){
this.HttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
this.HttpRequest.send(strData)
}else{
this.HttpRequest.send();
}
},
_serialize:function(data){
var values = [];
for(var key in data){
var value = data[key];
if(typeof value =="object"){
value = jSON.stringify(value);
}
values.push(key+'='+value);
}
return values.join("&");
},
onSuccess:function(){
if(typeof this.success == "function"){
this.success();
}
},
onLoading:function(){
if(typeof this.loading == "function"){
this.loading();
}
}
}
//console.log(httpRequest);
//主函数
// var props = {url:async:dataType:}
var A = function(props){
this.HttpRequest = httpRequest;
for(var key in props){
proto[key] = props[key];
}
}
//扩展a
A.prototype = proto;
return A;
})();
//function sendData(){
// //用法
// alert("aaa");
// var a = new Ajax({url:"http://*.php",dataType:"json",onSuccess:function(){console.log("成功了");},onLoading:function(){console.log("发送中");}});
// a.get({data:11111});
// a.post({data:2222});
//}
//a.get();a.post();a.error();
自己封装ajax,json.
最新推荐文章于 2024-09-28 22:42:44 发布