当前位置 : 主页 > 网络编程 > JavaScript >

Myutil

来源:互联网 收集:自由互联 发布时间:2021-06-28
MyUtilCreator //工具类生成器var MyUtilCreator = {create: function(){var util = {};util.ajax = function(url, data, callback, tip, async){console.info("request__"+data);if(tip){console.info("正在"+tip+"...");}async = "boolean"==typeof
MyUtilCreator
//工具类生成器
var MyUtilCreator = {
	create: function(){
		var util = {};

		util.ajax = function(url, data, callback, tip, async){
			console.info("request__"+data);

			if(tip){console.info("正在"+tip+"...");}
			async = "boolean"==typeof(async) ? async : true;	//默认异步加载
			$.ajax({
				url: url,
				type: "post",
				data: data,
				async: async,
				cache: false,
				dataType: "json",
/*				xhr: function(){
					//初始化XMLHttpRequest
					var xhr;
					if(window.XMLHttpRequest){
						xhr = new XMLHttpRequest();
					}else{
						xhr = new ActiveXObject("Microsoft.XMLHTTP");
					}
					alert(xhr);
					xhr.open("post", url, true);
					return xhr;
				},*/
				success: function(ret, status, xhr){
					console.info("response__"+JSON.stringify(ret));
					if(ret){
						if(callback && (Object.prototype.toString.call(callback)==='[object Function]')){
							callback(ret);
						}
					}else if(tip){
						console.info(tip+"失败");
					}
				},
				error: function(xhr, errorType, error){
					if(tip){
						console.info(tip+"失败,请检查网络是否异常");
					}
				}/*,  //安卓微信下报错, shit!
				beforeSend(xhr, settings){
					if(tip){
						console.info("正在"+tip+"...");
					}
				}*/
			});
		}
		
		util.setStorage = function(name, value){
			if(!name || !value)	return false;
			localStorage.setItem(name, JSON.stringify(value));
		}
		util.getStorage = function(name){
			if(!name) return null;
			var value = localStorage.getItem(name);
			if(value){
				try{
					return JSON.parse(value);
				}catch(e){
					return value;
				}
			}
		}
		util.rmStorage = function(name){
			if(!name)	return false;
			localStorage.removeItem(name);
		}

		util.setCookie = function(name, value, days, path){
			if(!name || !value)	return false;
			if(!days)	days=1;
			if(!path)	path="/";
		    var d = new Date();
		    d.setTime(d.getTime() + days*24*3600*1000);
		    document.cookie = name + "=" + JSON.stringify(value) + "; expires=" + d.toUTCString() + "; path="+path;
		}
		util.getCookie = function(name){
			if(!name)	return null;
		    var arr = document.cookie.split("; ");
		    for(var i = 0; i < arr.length; i++){
		        var temp = arr[i].split("=");
		        if(temp[0] == name){
			        try{
						return JSON.parse(temp[1]);
					}catch(e){
						return temp[1];
					}
		        }
		    }
		    return "";
		}
		util.rmCookie = function(name, path){
			if(!name)	return false;
			if(!path)	path="/";
		    var d = new Date();
		    d.setTime(d.getTime() - 10000);
		    var val = JSON.stringify(this.getCookie(name));
		    document.cookie = name + "="+val+"; expires=" + d.toUTCString() + "; path="+path;
		}

		//判断微信浏览器
		util.isWx = function(){
			var ua = navigator.userAgent.toLowerCase();
			return ua.match(/MicroMessenger/i)=="micromessenger";
		}
		
		util.isIos = function(){
			var ua = navigator.userAgent;
			return !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
		}

		//日期格式化
		util.formatDate = function(fmt, date){
			if(!fmt) return "";
			if(!date) date = new Date();
			var o = {
				"M+": date.getMonth() + 1, //月份 
				"d+": date.getDate(), //日 
				"h+": date.getHours(), //小时 
				"m+": date.getMinutes(), //分 
				"s+": date.getSeconds(), //秒 
				"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
				"S": date.getMilliseconds() //毫秒 
			};
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
			for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			return fmt;
		}
		
		function Rad(d){
			return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
		}
		//计算距离,参数分别为第一点的纬度,经度;第二点的纬度,经度
		util.getDistance = function(lat1,lng1,lat2,lng2){
	        var radLat1 = Rad(lat1);
	        var radLat2 = Rad(lat2);
	        var a = radLat1 - radLat2;
	        var  b = Rad(lng1) - Rad(lng2);
	        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
	        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	        s = s *6378.137 ;// EARTH_RADIUS;
	        s = Math.round(s * 10000) / 10000; //输出为公里
	        s=s.toFixed(2);
	        return s;
		}

		//仿表单请求
		util.postForm = function(url, obj){
		    var form = document.createElement("form");
		    form.action = url;
		    form.method = "post";
		    form.style.display = "none";
		    for (var x in obj) {
		        var opt = document.createElement("input");
		        opt.name = x;
		        opt.value = obj[x];
		        form.appendChild(opt);
		    }
		    document.body.appendChild(form);
		    form.submit();
		    return form;
		}

		// 是否为数组对象
		util.isArray = function(obj) {
			return Object.prototype.toString.call(obj)==='[object Array]';
		}

		// 将对象转换成url参数格式 a=123&b=456
		util.toUrlParas = function(obj){
			if(!obj)  return "";
			if("string" == typeof(obj)){
				return obj;
			}

			var paraStr = "";
			var isFirst = true;
			for(var x in obj){
				if(util.isArray(obj[x])){
					for(i in obj[x]) {
						if(!isFirst){
							paraStr += "&";
						}else{
							isFirst = false;
						}
						paraStr += x+"="+obj[x][i];
					}
				}else{
					if(!isFirst){
						paraStr += "&";
					}else{
						isFirst = false;
					}
					paraStr += x+"="+obj[x];
				}
			}
			return paraStr;
		}

		return util;
	}
};


//表单直接序列化为json
$.fn.serializeObj = function(){
	var o = {};
	var a = this.serializeArray();
	$.each(a, function(){
		if(o[this.name]){
			if (!o[this.name].push){
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		}else{
			o[this.name] = this.value || '';
		}
	});
	return o;
};
网友评论