[置顶] Jquery easyui+Jsonp+asp.net+翻页 事件版
Jquery easyui+Jsonp+asp.net+翻页 事件版
说明
Jsonp原理介绍:http://www.jb51.net/article/31167.htm
说明:这个是纯事件翻页,如果正常开发(小弟才疏学浅自己认为的),是需要靠参数传递来翻页不需要自己定义翻页事件,我这里是为了了解才这样做的,具体请看Test1/Default.aspx.exclude
构造文件
basic.html
显示页面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <meta charset="UTF-8"/> <title>用户信息列表</title> <link rel="stylesheet" type="text/css" href="../themes/default/easyui.css"/> <link rel="stylesheet" type="text/css" href="../themes/icon.css"/> <link rel="stylesheet" type="text/css" href="../demo/demo.css"/> <script type="text/javascript" src="../JS/jquery.min.js"></script> <script type="text/javascript" src="../JS/jquery.easyui.min.js"></script> </head> <body> <h2>用户信息列表</h2> <div class="demo-info" style="margin-bottom:10px;"> <div class="demo-tip icon-tip"></div> <div>全部用户信息列表.</div> </div> <div style="margin:10px 0"> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="Add()">Add</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="Update()">Update</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="Delete()">Delete</a> </div> <table id="tg" class="easyui-datagrid" title="用户信息列表" style="width:700px;height:350px" data-options=" singleSelect:true, collapsible:true, autoRowHeight:false, fitColumns:true, pagination:true, pageSize:10, pageList:[10,20,50,100], rownumbers:true, toolbar:'#tb', striped:true "> <thead> <tr> <th data-options="field:'ck',checkbox:true"></th> <th data-options="field:'userId',width:80">用户ID</th> <th data-options="field:'userName',width:100">用户名称</th> <th data-options="field:'age',width:80,align:'right'">年龄</th> <th data-options="field:'phone',width:80">手机</th> <th data-options="field:'address',width:250">地址</th> </tr> </thead> </table> <div id="update" class="easyui-window" title="修改用户信息" data-options="modal:true,closed:true,collapsible:false,minimizable:false,maximizable:false,iconCls:'icon-save'" style="width:500px;height:300px;padding:10px 50px;"> <form id="from_user" name="from_user" style="width:100%;height:100%"> <table style="width:100%;height:100%"> <tr> <td>用户ID:</td> <td><input class="easyui-validatebox" type="text" id="txtuserId" name="txtuserId" data-options="required:true" disabled="disabled" readonly="readonly"/></td> </tr> <tr> <td>用户名称:</td> <td><input class="easyui-validatebox" type="text" id="txtuserName" name="txtuserName" data-options="required:true,validType:'length[2,10]'"/></td> </tr> <tr> <td>年龄:</td> <td><input class="easyui-numberbox" id="txtage" name="txtage" data-options="required:true"/></td> </tr> <tr> <td>手机:</td> <td><input class="easyui-validatebox" type="text" id="txtphone" name="txtphone" data-options="required:true,validType:'phone'"/></td> </tr> <tr> <td>地址:</td> <td><input class="easyui-validatebox" type="text" id="txtaddress" name="txtaddress" data-options="validType:'length[0,20]'"/></td> </tr> <tr> <td>用户类型:</td> <td><input class="easyui-combobox" id="txttype" name="txttype" data-options="valueField:'id',textField:'text',panelHeight:'auto',editable:false,value:'1'"/></td> </tr> <tr> <td colspan="2"> <a id="save" href="javascript:void(0)" class="easyui-linkbutton">Save</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="cancel()">Cancel</a> </td> </tr> </table> </form> </div> <div id="tb" style="height:auto;"> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" onclick="Add()">Add</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true" onclick="Update()">Update</a> <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" onclick="Delete()">Delete</a> </div> <script type="text/javascript"> $(document).ready(function(){ loadData(0,10); loadCombobox(); $('#tg').datagrid('getPager').pagination({ onSelectPage:SelectPage, onBeforeRefresh:SelectPage, beforePageText:'第', afterPageText:'页 共{pages}页', displayMag:'当前显示 {from} - {to} 条记录 共 {total} 条记录' }); }); function loadCombobox(){ $.ajax({ type:"get", async:false, url:'Handler.ashx?cmd=GetUserType', dataType:"jsonp", jsonp:'callback', jsonpCallback:'_dg_loadData', success:function(json){ $('#txttype').combobox('loadData',json); }, error:function(error,state){ $.messager.alert('系统提示',error+" -1 "+state,'error'); } }); } function pagerFilter(data){ if (typeof data.length == 'number' && typeof data.splice == 'function'){ // is array data = { total: data.length, rows: data } } var dg = $(this); var opts = dg.datagrid('options'); var pager = dg.datagrid('getPager'); pager.pagination({ onSelectPage:function(pageNum, pageSize){ opts.pageNumber = pageNum; opts.pageSize = pageSize; // pager.pagination('refresh',{ // pageNumber:pageNum, // pageSize:pageSize // // }); loadData((opts.pageNumber-1)*parseInt(opts.pageSize),start + parseInt(opts.pageSize)); } }); if (!data.originalRows){ data.originalRows = (data.rows); } var start = (opts.pageNumber-1)*parseInt(opts.pageSize); var end = start + parseInt(opts.pageSize); data.rows = (data.originalRows.slice(start, end)); return data; } function SelectPage(pageNum, pageSize){ var opts = $('#tg').datagrid('options'); opts.pageNumber = pageNum; opts.pageSize = pageSize; loadData((opts.pageNumber-1)*parseInt(opts.pageSize),(opts.pageNumber-1)*parseInt(opts.pageSize) + parseInt(opts.pageSize)); } function loadData(start,end){ $.ajax({ type:"get", async:false, url:'Handler.ashx?cmd=GetUserName&start='+start+'&end='+end, dataType:"jsonp", jsonp:'callback', jsonpCallback:'_dg_loadData', success:function(json){ $('#tg').datagrid('loadData',json); }, error:function(error,state){ $.messager.alert('系统提示',error+" 0 "+state,'error'); } }); } function Add(){ cancel(); $('#save').unbind().bind('click',UserSave); $('#update').window('open'); } function Update(){ var row=$('#tg').datagrid('getSelected'); if(row){ $('#txtuserId').val(row.userId); $.ajax({ type:'get', async:false, url:'Handler.ashx', data:"cmd=GetUser&userId="+escape(row.userId), dataType:"jsonp", jsonp:'callback', jsonpCallback:'_dg_loadData', success:function(json){ $('#txtuserName').val(json.userName); // $('#txtage').val(json.age); // $('input[name="txtage"]').attr('value',row.age); $('#txtage').numberbox('setValue',json.age); $('#txtphone').val(json.phone); $('#txtaddress').val(json.address); $('#txttype').combobox('setValue',json.type); $('#save').unbind().bind('click',UserUpdate); $('#update').window('open'); }, error:function(error,state){ $.messager.alert('系统提示',error+" 1 "+state,'error'); } }); } } function Delete(){ var row=$('#tg').datagrid('getSelected'); if(row){ $.messager.confirm('系统提示','是否删除该用户信息?',function(result){ if(result){ UserDelete(row.userId) } }); } } function UserSave(){ if(!$('#from_user').form('validate')){ return; } var txtuserId=$('#txtuserId').val(); var txtuserName=$('#txtuserName').val(); var txtage=$('#txtage').val(); var txtphone=$('#txtphone').val(); var txtaddress=$('#txtaddress').val(); var txttype=$('#txttype').combobox('getValue'); $.ajax({ type:'get', async:false, url:'Handler.ashx', data:"cmd=SaveUserName&userId="+escape($('#txtuserId').val())+"&userName="+escape($('#txtuserName').val())+"&age="+escape($('#txtage').val())+ "&phone="+escape($('#txtphone').val())+"&address="+escape($('#txtaddress').val())+"&type="+escape($('#txttype').combobox('getValue')), dataType:"jsonp", jsonp:'callback', jsonpCallback:'_dg_loadData', success:function(json){ // $('#tg').datagrid('loadData',json); SelectPage($('#tg').datagrid('options').pageNumber,$('#tg').datagrid('options').pageSize); $.messager.alert('系统提示','添加用户信息成功.','info'); $('#update').window('close'); }, error:function(error,state){ $.messager.alert('系统提示',error+" 1 "+state,'error'); } }); } function UserUpdate(){ if(!$('#from_user').form('validate')){ return; } var txtuserId=$('#txtuserId').val(); var txtuserName=$('#txtuserName').val(); var txtage=$('#txtage').val(); var txtphone=$('#txtphone').val(); var txtaddress=$('#txtaddress').val(); var txttype=$('#txttype').combobox('getValue'); $.ajax({ type:'get', async:false, url:'Handler.ashx', data:"cmd=UpdateUserName&userId="+escape($('#txtuserId').val())+"&userName="+escape($('#txtuserName').val())+"&age="+escape($('#txtage').val())+ "&phone="+escape($('#txtphone').val())+"&address="+escape($('#txtaddress').val())+"&type="+escape($('#txttype').combobox('getValue')), dataType:"jsonp", jsonp:'callback', jsonpCallback:'_dg_loadData', success:function(json){ // $('#tg').datagrid('loadData',json); SelectPage($('#tg').datagrid('options').pageNumber,$('#tg').datagrid('options').pageSize); $.messager.alert('系统提示','更新用户信息成功.','info'); $('#update').window('close'); }, error:function(error,state){ $.messager.alert('系统提示',error+" 2 "+state,'error'); } }); } function UserDelete(userId){ if(!userId) return false; $.ajax({ type:'get', async:false, url:'Handler.ashx', data:"cmd=DeleteUserName&userId="+escape(userId), dataType:"jsonp", jsonp:'callback', jsonpCallback:'_dg_loadData', success:function(json){ // $('#tg').datagrid('loadData',json); SelectPage($('#tg').datagrid('options').pageNumber,$('#tg').datagrid('options').pageSize); $.messager.alert('系统提示','删除用户信息成功.','info'); $('#update').window('close'); }, error:function(error,state){ $.messager.alert('系统提示',error+" 3 "+state,'error'); } }); } function cancel(){ $('#txtuserId').val(''); $('#txtuserName').val(''); $('#txtage').val(''); $('input[name="txtage"]').attr(''); $('#txtphone').val(''); $('#txtaddress').val(''); $('#txttype').combobox('setValue','1'); $('#update').window('close'); } </script> </body> </html>
Handler.ashx
操作数据页面
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Reflection; using System.Collections.Generic; using System.Transactions; public class Handler : IHttpHandler { public List<User> users = new List<User>(); public void ProcessRequest (HttpContext context) { context.Response.ContentType = "application/jsonp"; string cmd = context.Request["cmd"]; if (!string.IsNullOrEmpty(cmd)) { MethodInfo Method = this.GetType().GetMethod(cmd,BindingFlags.NonPublic|BindingFlags.Instance); if (Method!=null) { Method.Invoke(this, new object[] { context }); } } } public bool IsReusable { get { return false; } } void GetUserType(HttpContext context) { string callback = context.Request["callback"]; string json = callback + "([" + "{\"id\":1,\"text\":\"普通用户\"}," + "{\"id\":2,\"text\":\"高级用户\"}," + "{\"id\":3,\"text\":\"铜牌用户\"}," + "{\"id\":4,\"text\":\"银牌用户\"}," + "{\"id\":5,\"text\":\"金牌用户\"}," + "{\"id\":6,\"text\":\"钻石用户\"}," + "])"; context.Response.Write(json); context.Response.End(); } void GetUserName(HttpContext context) { string callback = context.Request["callback"]; users = context.Cache["users"] as List<User>; if (users==null) { users = new List<User>(); } string json = callback + "({\"total\":" + users.Count + ",\"rows\":["; int start = int.Parse(context.Request["start"]); int end = int.Parse(context.Request["end"]); if (end>users.Count) { end = users.Count; } for (int i = start; i < end; i++) { User user = users[i]; json += "{\"userId\":" + user.userId + ",\"userName\":\"" + user.userName + "\",\"age\":" + user.age + ",\"phone\":\"" + user.phone + "\",\"address\":\"" + user.address + "\"},"; } json += "]})"; //string json = callback+"({\"total\":28,\"rows\":["+ // "{\"userId\":1,\"userName\":\"A1\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":2,\"userName\":\"A2\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":3,\"userName\":\"A3\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":4,\"userName\":\"A4\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":5,\"userName\":\"A5\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":6,\"userName\":\"A6\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":7,\"userName\":\"A7\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":8,\"userName\":\"A8\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":9,\"userName\":\"A9\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":10,\"userName\":\"A10\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":11,\"userName\":\"A11\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"},"+ // "{\"userId\":12,\"userName\":\"A12\",\"age\":18,\"phone\":\"15612345678\",\"address\":\"XXXXXXX\"}"+ // "]})"; context.Response.Write(json); context.Response.End(); } void UpdateUserName(HttpContext context) { string callback = context.Request["callback"]; users = context.Cache["users"] as List<User>; if (users == null) { users = new List<User>(); } string userId = context.Request["userId"]; string userName = context.Request["userName"]; string age = context.Request["age"]; string phone = context.Request["phone"]; string address = context.Request["address"]; string type = context.Request["type"]; //string json = callback + "({\"total\":" + users.Count + ",\"rows\":["; foreach (User user in users) { if (user.userId == int.Parse(userId)) { user.userName = userName; user.age = int.Parse(age); user.phone = phone; user.address = address; user.type = int.Parse(type); } } context.Cache.Remove("users"); context.Cache.Insert("users",users); //foreach (User user in users) //{ // json += "{\"userId\":" + user.userId + ",\"userName\":\"" + user.userName + "\",\"age\":" + user.age + ",\"phone\":\"" + user.phone + "\",\"address\":\"" + user.address + "\"},"; //} //json += "]})"; context.Response.Write(callback + "(1)"); context.Response.End(); } void SaveUserName(HttpContext context) { string callback = context.Request["callback"]; users = context.Cache["users"] as List<User>; if (users == null) { users = new List<User>(); } string userId = context.Request["userId"]; string userName = context.Request["userName"]; string age = context.Request["age"]; string phone = context.Request["phone"]; string address = context.Request["address"]; string type = context.Request["type"]; //string json = callback + "({\"total\":" + users.Count + ",\"rows\":["; using (TransactionScope transaction = new TransactionScope()) { User _users = new User(users[users.Count - 1].userId + 1, userName, int.Parse(age), phone, address,int.Parse(type)); users.Add(_users); context.Cache.Remove("users"); context.Cache.Insert("users", users); transaction.Complete(); } //foreach (User user in users) //{ // json += "{\"userId\":" + user.userId + ",\"userName\":\"" + user.userName + "\",\"age\":" + user.age + ",\"phone\":\"" + user.phone + "\",\"address\":\"" + user.address + "\"},"; //} //json += "]})"; context.Response.Write(callback + "(1)"); context.Response.End(); } void DeleteUserName(HttpContext context) { string callback = context.Request["callback"]; users = context.Cache["users"] as List<User>; if (users == null) { users = new List<User>(); } string userId = context.Request["userId"]; //string json = callback + "({\"total\":" + users.Count + ",\"rows\":["; User _user = null; foreach (User user in users) { if (user.userId == int.Parse(userId)) { _user = user; } } users.Remove(_user); context.Cache.Remove("users"); context.Cache.Insert("users", users); //foreach (User user in users) //{ // json += "{\"userId\":" + user.userId + ",\"userName\":\"" + user.userName + "\",\"age\":" + user.age + ",\"phone\":\"" + user.phone + "\",\"address\":\"" + user.address + "\"},"; //} //json += "]})"; context.Response.Write(callback+"(1)"); context.Response.End(); } void GetUser(HttpContext context) { string callback = context.Request["callback"]; users = context.Cache["users"] as List<User>; if (users == null) { users = new List<User>(); } string userId = context.Request["userId"]; string json = callback + "("; User _user = null; foreach (User user in users) { if (user.userId == int.Parse(userId)) { _user = user; } } json += "{\"userId\":" + _user.userId + ",\"userName\":\"" + _user.userName + "\",\"age\":" + _user.age + ",\"phone\":\"" + _user.phone + "\",\"address\":\"" + _user.address + "\",\"type\":\"" + _user.type + "\"}"; json += ")"; context.Response.Write(json); context.Response.End(); } }
Global.asax
初始化数据
<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { // 在应用程序启动时运行的代码 System.Collections.Generic.List<User> users = new System.Collections.Generic.List<User>(); for (int i = 1; i <= 100; i++) { users.Add(new User(i, "A" + i, new Random().Next(20), "15612345678", "XXXXXX" + new Random().Next(100), new Random().Next(1, 6))); } //建立回调委托的一个实例 CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(CacheItemRemoved); HttpContext.Current.Cache.Insert("users", users, null, DateTime.Now.AddDays(1), TimeSpan.Zero, CacheItemPriority.High, callBack); } void CacheItemRemoved(string key, object value, CacheItemRemovedReason reason) { System.Collections.Generic.List<User> users = new System.Collections.Generic.List<User>(); if(HttpContext.Current.Cache[key] != null){ HttpContext.Current.Cache.Remove(key); } users.Add(new User(-1,"缓存已被清除",-1,"---","清除原因:"+reason,1)); HttpContext.Current.Cache.Insert(key, users); } void Application_End(object sender, EventArgs e) { // 在应用程序关闭时运行的代码 } void Application_Error(object sender, EventArgs e) { // 在出现未处理的错误时运行的代码 } void Session_Start(object sender, EventArgs e) { // 在新会话启动时运行的代码 } void Session_End(object sender, EventArgs e) { // 在会话结束时运行的代码。 // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer // 或 SQLServer,则不会引发该事件。 } </script>
完成
Ok,用事件翻页已经好了,下载Demo