日期:2014-05-16  浏览次数:20369 次

__init_xu 色色js代码库_增加Ajax功能
xu.pkg('xu.net');

//xu.net.ajax({
//    url: 'reg.php',method: 'POST',
//    data: {user:$eo('user').val(),pwd:$eo('password').val()} //参数
//    success: function(responseText) {
//        $eo("tips").html(responseText) //传入函数的值以便给你操作。
//    }
//});


xu.apply(xu.net,{
	ajax: function(s,isnew){
		if (!xu.verify._obj(s)) return ;
		var data = s.data ? this._dataParser(s.data):null;
		with(this._getXhr(isnew)){ // this => xu.net
			open(s.method||"GET" ,s.url,((s.async!=undefined)?s.async:true));
			setRequestHeader("X_REQUESTED_WITH","xmlhttprequest");
			setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
			send(data);
			onreadystatechange=function(){// FF: this=>onreadystatechange;IE: this=>window				
				// readyState<3 读取status会出现未知错误
				if(readyState==4&&status==200){s.success(responseText)}
			};
		}
	} ,
	_dataParser: function(data){ // 从对象生成查询格式的字符串		
		if (!xu.verify._obj(data)) return null;
		var param_key = function(key,pkey){
			if(!pkey)return key ; 
			return pkey + '[' + key + ']' ;
		};
		var obj2qparams = function(obj,pkey){
			var qstr = '' ,pkey = pkey || null ;			
			for(var p in obj){
				if (obj.hasOwnProperty(p) && xu.verify._str(p)){
					if (xu.verify._obj(obj[p])){
						qstr += obj2qparams(obj[p],param_key(p,pkey));
					}else
						qstr += param_key(p,pkey) + '=' + obj[p] + '&' ;
				}
			}
			return qstr ;
		};
		// demo
//		data['user'] = {name:'se',ps:123,role:{name:'admin',group:{name:'backup'}}};
		return obj2qparams(data).replace(/&$/,'');
	} ,
	_xhr : null ,
	_getXhr: function(isNew){
		return isNew?this._newXhr():( this._xhr?this._xhr:(this._xhr=this._newXhr()) );
	},
	_newXhr: function(){return window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();} ,
	get: function(url,data,callback){
		this.ajax({url: url,data: data,success:callback});
	},
	post: function(url,data,callback){
		this.ajax({url: url,method:'POST',data: data,success:callback});
	}
});

xu.apply(xu.dom.EObject.prototype,{
	load: function(url,data,callback){
		var _this = this ;
		var callback = callback || function(rt){return rt;};
		xu.net.post(url,data,function(rt){
			rt = callback(rt,_this.ele);
			if (rt) _this.html(rt);
		});
	}
});

?