自己用的jquery经常用的工具command
var Cmd = { Entity: { QueryString: {}, }, RootPath: function () { var pathName = window.location.pathname.substring(1); var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/')); if (webName != "" && webName.toLowerCase() != "web_html") { return window.location.protocol + '//' + window.location.host + '/' + webName; } else { return window.location.protocol + '//' + window.location.host; } }, //======异步方法===== Ajax: function (url, data, success, error) { if (error) { $.ajax({ type: "Post", url: url, dataType: "json", data: data, success: success, //error: error }); } else { $.ajax({ type: "Post", url: url, dataType: "json", data: data, success: success, error: function (XmlHttpRequest, textStatus, errorThrown) { // alert(XmlHttpRequest.responseText); } }); } }, //=====同步方法==== AjaxAsync: function (url, data) { var result; $.ajax({ type: "post", url: url, data: data, // cache: false, async: false, dataType: "json", success: function (obj) { result = obj; } }); return result; }, //将后台时间转换为正常时间显示 FormatTime: function (time) { var time2 = JSON.stringify(time); var date = new Date(parseInt(time2.substr(7, 13))); return date.format("yyyy-MM-dd HH:mm:ss"); }, //将后台时间转换为正常时间显示 FormatMinute: function (time) { var time2 = JSON.stringify(time); var date = new Date(parseInt(time2.substr(7, 13))); return date.format("yyyy-MM-dd HH:mm"); }, FormatDataTime: function (time) { var time2 = JSON.stringify(time); var date = new Date(parseInt(time2.substr(7, 13))); return date.format("yyyy-MM-dd"); }, FormatDataMonth: function (time) { var time2 = JSON.stringify(time); var date = new Date(parseInt(time2.substr(7, 13))); return date.format("yyyy-MM"); }, //处理待html标签的数据公用方法 htmlTag: function (str) { return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) { return { '<': '<', '&': '&', '"': '"', '>': '>', ''': "'", ' ': ' ' }[m] }) : ''; }, //将标签内容中标签替换掉 removeHTMLTag: function (str) { str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白 str = str.replace(/ /ig, '');//去掉 return str; }, SubStrLength: function (str, len) { var strstring = (str == null ? "null" : str); return (strstring.length > len ? strstring.substring(0, len) + "..." : strstring); } }; RequestURLParms = (function () { var fn = function () { }; fn.prototype.QueryString2 = function (val) { var uri = window.location.search; var re = new RegExp("" + val + "=([^&?]*)", "ig"); return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null); } String.prototype.GetValue = function (parm) { var reg = new RegExp("(^|&)" + parm + "=([^&]*)(&|$)"); var r = this.substr(this.indexOf("\?") + 1).match(reg); if (r != null) return unescape(r[2]); return null; } fn.prototype.QueryString = function (key) { var url = location.href; return url.GetValue(key); } return new fn(); })(); Date.prototype.format = function (formatStr) { var date = this; /* 函数:填充0字符 参数:value-需要填充的字符串, length-总长度 返回:填充后的字符串 */ var zeroize = function (value, length) { if (!length) { length = 2; } value = new String(value); for (var i = 0, zeros = ''; i < (length - value.length) ; i++) { zeros += '0'; } return zeros + value; }; return formatStr.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function ($0) { switch ($0) { case 'd': return date.getDate(); case 'dd': return zeroize(date.getDate()); case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][date.getDay()]; case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()]; case 'M': return date.getMonth() + 1; case 'MM': return zeroize(date.getMonth() + 1); case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()]; case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()]; case 'yy': return new String(date.getFullYear()).substr(2); case 'yyyy': return date.getFullYear(); case 'h': return date.getHours() % 12 || 12; case 'hh': return zeroize(date.getHours() % 12 || 12); case 'H': return date.getHours(); case 'HH': return zeroize(date.getHours()); case 'm': return date.getMinutes(); case 'mm': return zeroize(date.getMinutes()); case 's': return date.getSeconds(); case 'ss': return zeroize(date.getSeconds()); case 'l': return date.getMilliseconds(); case 'll': return zeroize(date.getMilliseconds()); case 'tt': return date.getHours() < 12 ? 'am' : 'pm'; case 'TT': return date.getHours() < 12 ? 'AM' : 'PM'; } }); }; $(function () { var url = location.href.replace("#", ""); var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&"); for (var i = 0; j = paraString[i]; i++) { Cmd.Entity.QueryString[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length); } }); $(function () { jQuery('input:text:first').focus();//直接定位到当前页面的第一个文本框 var $inp = jQuery('input:text');//所有文本框 $inp.bind('keydown', function (e) { var key = e.which; if (key == 13) { e.preventDefault(); var nxtIdx = $inp.index(this) + 1; jQuery(":input:text:eq(" + nxtIdx + ")").focus(); } }); });
后台
public class SerializerHelp { public static byte[] JsonSerializerByte(object obj) { DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(obj.GetType()); MemoryStream memoryStream = new MemoryStream(); dataContractJsonSerializer.WriteObject(memoryStream, obj); byte[] array = new byte[memoryStream.Length]; memoryStream.Position = 0L; memoryStream.Read(array, 0, (int)memoryStream.Length); memoryStream.Close(); return array; } public static string JsonSerializerStr(object obj) { byte[] bytes = SerializerHelp.JsonSerializerByte(obj); return Encoding.UTF8.GetString(bytes); } public static T JsonDeserialize<T>(string json) where T : class, new() { byte[] bytes = Encoding.UTF8.GetBytes(json); return SerializerHelp.JsonDeserialize<T>(bytes); } public static T JsonDeserialize<T>(byte[] bytes) where T : class, new() { MemoryStream stream = new MemoryStream(bytes); T t = Activator.CreateInstance<T>(); DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(t.GetType()); return (T)((object)dataContractJsonSerializer.ReadObject(stream)); } }
public class RestAgent { private static byte[] InvokeRest(string address, string type, string param) { WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type:application/json; charset=utf-8"); webClient.Headers.Add("Accept-Language: zh-cn"); webClient.Headers.Add("Accept: */*"); webClient.Headers.Add(HttpRequestHeader.KeepAlive, "TRUE"); webClient.Headers.Add("Keep-Alive", "3000"); webClient.Headers.Add("Cache-Control: no-cache"); byte[] result; if (type != null && type.ToUpper() == "POST") { if (param != null && param.Trim() != "") { byte[] bytes = Encoding.UTF8.GetBytes(param); result = webClient.UploadData(address, bytes); } else { result = webClient.UploadData(address, null); } } else { string s = webClient.DownloadString(address); result = Encoding.UTF8.GetBytes(s); } return result; } /// <summary> /// 接口接收的数据转成代理对象 /// </summary> /// <typeparam name="T">实体对象:例如:pro_UserInfo</typeparam> /// <param name="address">接口地址:例如:www.testapi.com/user/getUserInfo</param> /// <param name="type">请求类型:Get,Post</param> /// <param name="param">请求的参数:Json转String,例如:"{\"UID\":\"abcdef\"}"</param> /// <returns>Rest<pro_UserInfo></returns> public static T InvokeRestObject<T>(string address, string type, string param) where T : new() { T t = (default(T) == null) ? Activator.CreateInstance<T>() : default(T); byte[] array = RestAgent.InvokeRest(address, type, param); T result; if (array == null || Encoding.UTF8.GetString(array) == "") { result = t; } else { result = RestAgent.JsonDeserial<T>(array); } return result; } /// <summary> /// 接口接收的数据转成代理对象集合 /// </summary> /// <typeparam name="T">实体对象:例如:pro_UserInfo</typeparam> /// <param name="address">接口地址:例如:www.testapi.com/user/getUserInfo</param> /// <param name="type">请求类型:Get,Post</param> /// <param name="param">请求的参数:Json转String,例如:"{\"UID\":\"abcdef\"}"</param> /// <returns>Rest<pro_UserInfo></returns> public static List<T> InvokeRestListObject<T>(string address, string type, string param) { byte[] array = RestAgent.InvokeRest(address, type, param); List<T> result; if (array == null || Encoding.UTF8.GetString(array) == "") { result = null; } else { result = RestAgent.JsonDeserials<T>(array); } return result; } /// <summary> /// 接口接收的数据转成代理字符串 /// </summary> /// <param name="address">接口地址:例如:www.testapi.com/user/getUserInfo</param> /// <param name="type">请求类型:Get,Post</param> /// <param name="param">请求的参数:Json转String,例如:"{\"UID\":\"abcdef\"}"</param> /// <returns>"{\"UID\":\"abcdef\"}"</returns> public static string InvokeRestString(string address, string type, string param) { byte[] bytes = RestAgent.InvokeRest(address, type, param); return Encoding.UTF8.GetString(bytes); } private static T JsonDeserial<T>(byte[] jsons) { MemoryStream memoryStream = new MemoryStream(jsons); DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T)); T result = (T)((object)dataContractJsonSerializer.ReadObject(memoryStream)); memoryStream.Close(); return result; } private static List<T> JsonDeserials<T>(byte[] jsons) { MemoryStream memoryStream = new MemoryStream(jsons); DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(List<T>)); List<T> result = (List<T>)dataContractJsonSerializer.ReadObject(memoryStream); memoryStream.Close(); return result; } }
var entity = SerializerHelp.JsonDeserialize<Summary>(context.Request["Summary"]);
传图片
FileReader: function () { if (this.files.length > 0) { $.showPreloader('上传中...'); var form = new FormData(); var filesize = 0; for (var i = 0; i < this.files.length; i++) { var file = this.files[i]; if (file.type != "image") var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { //localStorage.File = this.result; //location.href = "EditImage.html"; } form.append("file_" + i, file); filesize += file.size; } if (filesize > 4 * 1024 * 1024 || filesize <= 0) { alert("您的图片过大或者不符合要求"); $.hidePreloader(); return; } var fileObj = file; // js 获取文件对象 var UploadUrl = Cmd.RootPath() + "/Handlers/Upload.ashx?Command=UploadFlie&phoneNum=" + localStorage.ls_phoneNum + ""; // 接收上传文件的后台地址 // FormData 对象 form.append("author", "volcano");// 可以增加表单数据 var xhr = new XMLHttpRequest(); xhr.open("post", UploadUrl, true); xhr.onload = function (e) { $.hidePreloader(); var file = JSON.parse(e.target.response); //if (file.FilePaths[0]) { }; xhr.send(form); } }