• 一套手写ajax加一般处理程序的增删查改


    倾述下感受:8天16次驳回。这个惨不忍睹。

    好了不说了,说多了都是泪。

    直接上代码 :

    这个里面的字段我是用动软生成的,感觉自己手写哪些字段太浪费时间了,说多了都是泪

    ajax.model层的代码:

    using System;
    namespace Ajax.Model
    {
        /// <summary>
        /// SM_Class:实体类(属性说明自动提取数据库字段的描述信息)
        /// </summary>
        [Serializable]
        public partial class SM_Class
        {
            public SM_Class()
            {}
            #region Model
            private int _sm_id;
            private string _sm_name;
            private string _sm_grade;
            private string _sm_class;
            private string _sm_gender;
            private int? _sm_age;
            private DateTime _sm_outtime;
            private bool _sm_istf;
            /// <summary>
            /// 
            /// </summary>
            public int SM_id
            {
                set{ _sm_id=value;}
                get{return _sm_id;}
            }
            /// <summary>
            /// 
            /// </summary>
            public string SM_name
            {
                set{ _sm_name=value;}
                get{return _sm_name;}
            }
            /// <summary>
            /// 
            /// </summary>
            public string SM_Grade
            {
                set{ _sm_grade=value;}
                get{return _sm_grade;}
            }
            /// <summary>
            /// 
            /// </summary>
            public string SM_Classes
            {
                set{ _sm_class=value;}
                get{return _sm_class;}
            }
            /// <summary>
            /// 
            /// </summary>
            public string SM_Gender
            {
                set{ _sm_gender=value;}
                get{return _sm_gender;}
            }
            /// <summary>
            /// 
            /// </summary>
            public int? SM_Age
            {
                set{ _sm_age=value;}
                get{return _sm_age;}
            }
            /// <summary>
            /// 
            /// </summary>
            public DateTime SM_OutTime
            {
                set{ _sm_outtime=value;}
                get{return _sm_outtime;}
            }
            /// <summary>
            /// 
            /// </summary>
            public bool SM_Istf
            {
                set{ _sm_istf=value;}
                get{return _sm_istf;}
            }
            #endregion Model
    
        }
    }
    View Code

    ajax.dal层代码:

    第一个先上数据库连接帮助类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Ajax.DAL
    {
        //需要系统配置;系统设定;系统设置;查看系统配置程序集
        using System.Configuration;
        using System.Data.SqlClient;
        using System.Data;
       public class HelperSQL
        {
            //在ui的配置文件中配置AppSettings
           public static string str = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
    
           private static SqlConnection connection;
           public static SqlConnection Connection {
               get {
                   //判断是否有这个连接没有
                   if (connection == null) {
                       //创建连接
                       connection = new SqlConnection(str);
                       //打开连接
                       connection.Open();
                   }
                       //判断连接是否是关闭的
                   else if(connection.State==System.Data.ConnectionState.Closed){
                       //打开连接
                       connection.Open();
                   }
                       //判断连接是否中断
                   else if (connection.State == System.Data.ConnectionState.Broken) {
                       //先关闭连接
                       connection.Close();
                       //打开连接
                       connection.Open();
                   }
                   //返回连接
                   return connection;
               }
           }
    
           public static int ExecuteCommand(string strsql)
           {
               //传入数据库命令和连接
               SqlCommand sqlcmd = new SqlCommand(strsql, Connection);
               //执行语句返回受影响的行数
               int result = sqlcmd.ExecuteNonQuery();
               return result;
           }
           public static int ExecuteCommand(string strName, params SqlParameter[] values)
           {
               //传入数据库命令和连接
               SqlCommand sqlcmd = new SqlCommand(strName, Connection);
               //增加参数
               sqlcmd.Parameters.AddRange(values);
               return sqlcmd.ExecuteNonQuery();
           }
    
           public static DataSet GetDataSet(string strName)
           {
               //创建一个内存缓存
               DataSet ds = new DataSet();
               //传入命令和连接
               SqlCommand sqlcmd = new SqlCommand(strName, Connection);
               //创建一个桥接器
               SqlDataAdapter sqlda = new SqlDataAdapter(sqlcmd);
               //写入内存
               sqlda.Fill(ds);
               //返回
               return ds;
           }
    
           public static DataSet GetDataSet(string strName, params SqlParameter[] values)
           {
               //创建一个内存缓存
               DataSet ds = new DataSet();
               //传入命令和连接
               SqlCommand sqlcmd = new SqlCommand(strName, Connection);
               //增加参数
               sqlcmd.Parameters.AddRange(values);
               //打开桥连接
               SqlDataAdapter sqlda = new SqlDataAdapter(sqlcmd);
               //写入到内存
               sqlda.Fill(ds);
               //返回
               return ds;
           }
    
           public static DataSet StoredProcedure(string strName, params IDataParameter[] parmenters)
           {
               using (SqlConnection connection = new SqlConnection(str))
               {
                   //创建一个内存缓存
                   DataSet ds = new DataSet();
                   //创建一个桥连接
                   SqlDataAdapter sqlda = new SqlDataAdapter();
                   //告诉桥连接这个是存储过程
                   sqlda.SelectCommand = StoredProcedureCommand(connection, strName, parmenters);
                   //写入内存
                   sqlda.Fill(ds);
                  //返回
                   return ds;
               }
           }
           private static SqlCommand StoredProcedureCommand(SqlConnection sqlcc, string strName, IDataParameter[] parmenters) {
               //传入存储过程名称和连接数据库命令
               SqlCommand sqlcmd = new SqlCommand(strName, sqlcc);
               //告诉数据库这个是存储过程
               sqlcmd.CommandType = CommandType.StoredProcedure;
               foreach (var item in parmenters)
               {
                   if (item !=null)
                   {
                       //判断的参数是输入输出或者参数是输入并且参数不能为空
                       if ((item.Direction==ParameterDirection.InputOutput||
                      
                           item.Direction==ParameterDirection.Input  )&&
                      
                           (item.Value==null))
                       {
                           //该类区分空值(空对象)和未初始化值
                           item.Value = DBNull.Value;
                       }
                       //加入这个参数
                       sqlcmd.Parameters.Add(item);
                   }      
               }
               //返回连接和命令
               return sqlcmd;
           }
       }
    }
    View Code

    ajax.dal 实现的增删查改

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Ajax.DAL
    {
        using Ajax.Model;
        using System.Data;
        using System.Data.SqlClient;
      public   class AjaxSM_Class
        {
          /// <summary>
          /// 新增
          /// </summary>
          /// <param name="model"></param>
          /// <returns></returns>
          public int Add(SM_Class model) {
              StringBuilder strSql = new StringBuilder();
              strSql.Append("insert into SM_Class(");
              strSql.Append("SM_name,SM_Grade,SM_Class,SM_Gender,SM_Age,SM_OutTime,SM_Istf)");
              strSql.Append(" values (");
              strSql.Append("@SM_name,@SM_Grade,@SM_Class,@SM_Gender,@SM_Age,@SM_OutTime,@SM_Istf)");
              strSql.Append(";select @@IDENTITY");
              SqlParameter[] parameters = {
                        new SqlParameter("@SM_name", SqlDbType.VarChar,20),
                        new SqlParameter("@SM_Grade", SqlDbType.VarChar,20),
                        new SqlParameter("@SM_Class", SqlDbType.VarChar,20),
                        new SqlParameter("@SM_Gender", SqlDbType.VarChar,4),
                        new SqlParameter("@SM_Age", SqlDbType.Int,4),
                        new SqlParameter("@SM_OutTime", SqlDbType.DateTime),
                        new SqlParameter("@SM_Istf", SqlDbType.Bit,1)};
              parameters[0].Value = model.SM_name;
              parameters[1].Value = model.SM_Grade;
              parameters[2].Value = model.SM_Classes;
              parameters[3].Value = model.SM_Gender;
              parameters[4].Value = model.SM_Age;
              parameters[5].Value = model.SM_OutTime;
              parameters[6].Value = model.SM_Istf;
    
              object obj = HelperSQL.ExecuteCommand(strSql.ToString(), parameters);
              if (obj == null)
              {
                  return 0;
              }
              else
              {
                  return Convert.ToInt32(obj);
              }
          
          }
          /// <summary>
          /// 删除
          /// </summary>
          /// <param name="SM_id"></param>
          /// <returns></returns>
          public int Delete(int SM_id)
          {
    
              StringBuilder strSql = new StringBuilder();
              strSql.Append("UPDATE SM_Class SET SM_Istf=0  ");
              strSql.Append("  WHERE SM_id=@SM_id");
              SqlParameter[] parameters = {
                        new SqlParameter("@SM_id", SqlDbType.Int,4)
                };
              parameters[0].Value = SM_id;
    
              int rows = HelperSQL.ExecuteCommand(strSql.ToString(), parameters);
              return rows;
          }
    
          /// <summary>
          /// 获得所有数据
          /// </summary>
          /// <param name="strWhere"></param>
          /// <returns></returns>
          public List<SM_Class> GetList()
          {
              StringBuilder strSql = new StringBuilder();
              List<SM_Class> list = new List<SM_Class>();
              strSql.Append("select SM_id,SM_name,SM_Grade,SM_Class,SM_Gender,SM_Age,SM_OutTime,SM_Istf ");
              strSql.Append(" FROM SM_Class ");
             //获取dataset从表中读取
              DataSet ds= HelperSQL.GetDataSet(strSql.ToString());
              DataTable dt = ds.Tables[0];
              foreach (DataRow item in dt.Rows)
              {  
                  //得到一个sm_class 类
                  SM_Class smc = DataModel(item);
                  //加入到list集合中
                  list.Add(smc);
              }
              return list;
          }
          /// <summary>
          /// 更具id找一条数据
          /// </summary>
          /// <param name="SM_id"></param>
          /// <returns></returns>
          public List<SM_Class> GetList( int  SM_id) {
              StringBuilder strSql = new StringBuilder();
              List<SM_Class> list = new List<SM_Class>();
              strSql.Append("select  top 1 SM_id,SM_name,SM_Grade,SM_Class,SM_Gender,SM_Age,SM_OutTime,SM_Istf from SM_Class ");
              strSql.Append("  where SM_id=@SM_id");
              SqlParameter[] parameters = {
                        new SqlParameter("@SM_id", SqlDbType.Int,4)
                };
              parameters[0].Value = SM_id;
              DataSet ds = HelperSQL.GetDataSet(strSql.ToString(),parameters);
              DataTable dt = ds.Tables[0];
              foreach (DataRow item in dt.Rows)
              {
                  //得到一个sm_class 类
                  SM_Class smc = DataModel(item);
                  //加入到list集合中
                  list.Add(smc);
              }
              return list;
          }
          /// <summary>
          /// 得到一个实体
          /// </summary>
          /// <param name="row"></param>
          /// <returns></returns>
          private SM_Class DataModel(DataRow row) {
              SM_Class model = new SM_Class();
              if (row != null)
              {
                  if (row["SM_id"] != null && row["SM_id"].ToString() != "")
                  {
                      model.SM_id = int.Parse(row["SM_id"].ToString());
                  }
                  if (row["SM_name"] != null)
                  {
                      model.SM_name = row["SM_name"].ToString();
                  }
                  if (row["SM_Grade"] != null)
                  {
                      model.SM_Grade = row["SM_Grade"].ToString();
                  }
                  if (row["SM_Class"] != null)
                  {
                      model.SM_Classes = row["SM_Class"].ToString();
                  }
                  if (row["SM_Gender"] != null)
                  {
                      model.SM_Gender = row["SM_Gender"].ToString();
                  }
                  if (row["SM_Age"] != null && row["SM_Age"].ToString() != "")
                  {
                      model.SM_Age = int.Parse(row["SM_Age"].ToString());
                  }
                  if (row["SM_OutTime"] != null && row["SM_OutTime"].ToString() != "")
                  {
                      model.SM_OutTime = DateTime.Parse(row["SM_OutTime"].ToString());
                  }
                  if (row["SM_Istf"] != null && row["SM_Istf"].ToString() != "")
                  {
                      if ((row["SM_Istf"].ToString() == "1") || (row["SM_Istf"].ToString().ToLower() == "true"))
                      {
                          model.SM_Istf = true;
                      }
                      else
                      {
                          model.SM_Istf = false;
                      }
                  }
              }
              return model;
          }
          /// <summary>
          /// 更新操作
          /// </summary>
          /// <param name="model"></param>
          /// <returns></returns>
          public int Update(SM_Class model) {
              StringBuilder strSql = new StringBuilder();
              strSql.Append("update SM_Class set ");
              strSql.Append("SM_name=@SM_name,");
              strSql.Append("SM_Grade=@SM_Grade,");
              strSql.Append("SM_Class=@SM_Class,");
              strSql.Append("SM_Gender=@SM_Gender,");
              strSql.Append("SM_Age=@SM_Age,");
              strSql.Append("SM_OutTime=@SM_OutTime,");
              strSql.Append("SM_Istf=@SM_Istf");
              strSql.Append(" where SM_id=@SM_id");
              SqlParameter[] parameters = {
                        new SqlParameter("@SM_name", SqlDbType.VarChar,20),
                        new SqlParameter("@SM_Grade", SqlDbType.VarChar,20),
                        new SqlParameter("@SM_Class", SqlDbType.VarChar,20),
                        new SqlParameter("@SM_Gender", SqlDbType.VarChar,4),
                        new SqlParameter("@SM_Age", SqlDbType.Int,4),
                        new SqlParameter("@SM_OutTime", SqlDbType.DateTime),
                        new SqlParameter("@SM_Istf", SqlDbType.Bit,1),
                        new SqlParameter("@SM_id", SqlDbType.Int,4)};
              parameters[0].Value = model.SM_name;
              parameters[1].Value = model.SM_Grade;
              parameters[2].Value = model.SM_Classes;
              parameters[3].Value = model.SM_Gender;
              parameters[4].Value = model.SM_Age;
              parameters[5].Value = model.SM_OutTime;
              parameters[6].Value = model.SM_Istf;
              parameters[7].Value = model.SM_id;
              int rows = HelperSQL.ExecuteCommand(strSql.ToString(), parameters);
              return rows;
          }
        }
    }
    View Code

    ajax.bll层代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Ajax.BLL
    {
        using Ajax.DAL;
        using Ajax.Model;
      public  class AjaxSM_Class
      {
          Ajax.DAL.AjaxSM_Class asmc = new DAL.AjaxSM_Class();
          /// <summary>
          /// 新增
          /// </summary>
          /// <param name="model"></param>
          /// <returns></returns>
          public int Add(SM_Class model)
          {
              return asmc.Add(model);
          }
          /// <summary>
          /// 删除
          /// </summary>
          /// <param name="SM_id"></param>
          /// <returns></returns>
          public int Delete(int SM_id)
          {
              return asmc.Delete(SM_id);
          }
    
          /// <summary>
          /// 获得所有数据
          /// </summary>
          /// <param name="strWhere"></param>
          /// <returns></returns>
          public List<SM_Class> GetList()
          {
              return asmc.GetList();
          }
          /// <summary>
          /// 更具id找一条数据
          /// </summary>
          /// <param name="SM_id"></param>
          /// <returns></returns>
          public List<SM_Class> GetList(int SM_id)
          {
              return asmc.GetList(SM_id);
          }
    
          /// <summary>
          /// 更新操作
          /// </summary>
          /// <param name="model"></param>
          /// <returns></returns>
          public int Update(SM_Class model)
          {
              return asmc.Update(model);
          }
      
        }
    }
    View Code

    ajax.ui层代码:

    先说js脚本把,这里是自己封装的一个ajax.js脚本  就是调用自己手写的这个ajaxhelper.js来实现异步刷新请求。

    var ajaxHelper = {
        markXHR: function () {
            var xhr;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else { xhr = new ActiveXObject("Micrsoft.XMLHTTP"); }
            return xhr;
        },
        //get请求
        ajaxGet: function (url, sucessFun) {
            this.ajaxOpt("get", url,null, sucessFun);
        },
        //post请求
        ajaxPost: function (url, data, sucessFun) {
            this.ajaxOpt("post", url, data, sucessFun);
        },
        //定义ajax的get和post请求
        //httpmenthod :get,post
        //data:发送给服务器的数据,post有值,get为null
        //sucessFun成功的回掉函数
        ajaxOpt: function (httpMenthod, url, data, sucessFun) {
            //转换成小写字符串
            var menthod = httpMenthod.toLowerCase();
            //定义xmlhttprequest对象
            var ajaxobj = this.markXHR();
            //异步对象设置参数,总是异步true
            ajaxobj.open(httpMenthod, url, true);
            //判断是get还上post,设置响应报文
            if (menthod == "get") {
                //为了使get请求不取自浏览器缓存,而每次都请求服务器
               
                ajaxobj.setRequestHeader("If-Modified-Since", "0");
            } else {
                //告诉服务器请求的数据类型
                ajaxobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            //给一度对象设置回掉函数
        
            ajaxobj.onreadystatechange = function () {
                if (ajaxobj.readyState==4&&ajaxobj.status==200) {
                    var jsonobj = JSON.parse(ajaxobj.responseText);
                    if (jsonobj.Status == "sucess") {
                        sucessFun(jsonobj);
                    }
                    else {
                        alert(jsonobj.Msg);
                    }
                    
                }
            }
            ajaxobj.send(data);
        }
    
    }
    View Code

    再者我有引用jquery-1.9.1.js 文件 还有一个msgBox.js作为弹出窗体,jquery我想大家应该都有,我就上传下msgBox的js文件的代码吧。

    /*{
        imghref:图片文件夹所在路径,
        waitImg:等待图片名,
        bgImg:背景图片名
       }
    */
    function MsgBox(s) {
        var secondConst = 2000;//系统默认显示时间
        var secondWait = 2000;//显示时间
        var timer;//计时器
        var lf, tp;//左边距,顶边距
        var paras = {}; //json参数
        function readyMsgBox() {
            if (s != null){
                if (s.imghref != null) paras.imghref = s.imghref; else paras.imghref = "images/";
                if (s.waitImg != null) paras.waitImg = s.waitImg; else paras.waitImg = "loader.gif";
                if (s.bgImg != null) paras.bgImg = s.bgImg; else paras.bgImg = "qzonebg.gif";
            }
            else paras = { imghref: "./images/", waitImg: "loader.gif", bgImg: "qzonebg.gif" };
            paras.waitImgTag = "<img src='" + paras.imghref + paras.waitImg + "' style='margin-right:10px;' align='middle'/>    ";
            preloadImg(new Array(paras.imghref + paras.bgImg, paras.imghref + paras.waitImg));
            writeMsgBox();
            window.onresize = function(){setPosition();}
        }
        this.showMsgWait = function (msg) {
            this.showMsgAllT(paras.waitImgTag + msg, 0);
        }
        this.showMsgAllT = function (msg, type) {
            clearTimer();
            changeIco(type);
            gelContainer().innerHTML = msg;
            showBox();
        }
        this.hidBox = function () { hideBox(); };
        this.showMsgText = function (msg) {
            this.showMsgAllT(msg, 0);
        }
        this.showMsgInfo = function (msg) {
            if (arguments.length > 1) paras.callBack = arguments[1];
            showSysMsg(msg, 1);
        }
        this.showMsgInfoSide = function (eleId, msg, doHid) {//doHid 是否消失
            if (arguments.length > 3) paras.callBack = arguments[1];
            showSysMsgSideEle(eleId, msg, 1, doHid);
        }
        function analysisPara(args) {
            if (args.length > 1) paras.callBack = args[1];
        }
        this.showMsgOk = function (msg) {
            if (arguments.length > 1) paras.callBack = arguments[1];
            showSysMsg(msg, 2);
        }
        this.showMsgOkSide = function (eleId, msg, doHid) {
            if (arguments.length > 3) paras.callBack = arguments[1];
            showSysMsgSideEle(eleId, msg, 2, doHid);
        }
        this.showMsgErr = function (msg) {
            if (arguments.length > 1) paras.callBack = arguments[1];
            showSysMsg(msg, 3);
        }
        this.showMsgErrSide = function (eleId,msg,doHid) {
            if (arguments.length > 3) paras.callBack = arguments[1];
            showSysMsgSideEle(eleId, msg, 3, doHid);
        }
        this.showSysMsgWTime = function (msg, type, second) {
            if (arguments.length > 3) paras.callBack = arguments[3];
            changeIco(type);
            gelContainer().innerHTML = msg;
            showBox();
            secondWait = second;
            if (second >= 0)
                startTimer(emptyMsg);
        }
        function showSysMsg(msg, type) {
            changeIco(type);
            gelContainer().innerHTML = msg;
            showBox();
            secondWait = secondConst;
            startTimer(emptyMsg);
        }
        //---显示在元素右边
        function showSysMsgSideEle(eleId, msg, type, doHid) {
            changeIco(type);
            gelContainer().innerHTML = msg;
            setPosSideEle(eleId);
            if (doHid) {
                secondWait = secondConst;
                startTimer(emptyMsg);
            } else clearTimer();
        }
        function setPosSideEle(eleId) {
            var wid = document.getElementById(eleId).offsetWidth;
            var hig = document.getElementById(eleId).offsetHeight;
            var pos = getPos(eleId);
            gelBox().style.left = (wid+2 + pos.left) + "px";
            gelBox().style.top = (pos.top - (hig/2)) + "px";
            gelBox().style.display = "block";
        }
        //--------------
        this.showReqErr=function(){this.showMsgErr("请求错误 ToT!");}
        this.showReqOk=function(){this.showMsgOk("操作成功 ^o^!");}
        this.showReqVF = function () { this.showSysMsgWTime("会话过期,3秒后自动返回登录界面 -o-!",1,3000); }
        this.showWait = function () { this.showMsgWait("请稍后 l _ l ..."); }
        //-------------
        function startTimer(functionName) {
            clearTimer();
            timer=window.setTimeout(functionName, secondWait);
        }
        function clearTimer() {
            if (timer != null && timer != undefined) { clearTimeout(timer); }
        }
        function emptyMsg() {
            gelContainer().innerHTML = "";
            hideBox();
            if (paras.callBack != null) {paras.callBack(); paras.callBack = null; }
        }
        function writeMsgBox() {
            var msgBox = document.createElement("table");
            var msgTbody = document.createElement("tbody");
            var msgTr = document.createElement("tr");
            var msgBoxL = document.createElement("td");
            var msgBoxC = document.createElement("td");
            var msgBoxR = document.createElement("td");
            document.body.appendChild(msgBox);
            msgBox.appendChild(msgTbody);
            msgTbody.appendChild(msgTr);
            msgTr.appendChild(msgBoxL);
            msgTr.appendChild(msgBoxC);
            msgTr.appendChild(msgBoxR);
            msgBox.setAttribute("id", "msgBox");
            msgBox.setAttribute("cellpadding", "0");
            msgBox.setAttribute("cellspacing", "0");
            msgBox.style.cssText = "height:52px;auto;position:absolute;z-index:999999;display:none; background:url(" + paras.imghref + paras.bgImg+") 0px -161px;";
            msgBoxL.setAttribute("id", "msgBoxL");
            msgBoxL.style.cssText = "50px;background:url(" + paras.imghref + paras.bgImg+") -7px -108px no-repeat;";
            msgBoxC.setAttribute("id", "msgBoxC");
            msgBoxC.style.cssText = "auto;line-height:51px;color:#666666;font-weight:bold;font-size:14px;padding-right:10px;";
            msgBoxR.setAttribute("id", "msgBoxR");
            msgBoxR.style.cssText = "5px;background:url(" + paras.imghref + paras.bgImg+") 0px 0px no-repeat;";
        }
        function changeIco(ty) {
            if (ty == 0)//none
                document.getElementById("msgBoxL").style.width = "10px";
            else document.getElementById("msgBoxL").style.width = "50px";
            if (ty == 1)//info
                document.getElementById("msgBoxL").style.backgroundPosition = "-7px -54px";
            else if (ty == 2)//ok
                document.getElementById("msgBoxL").style.backgroundPosition = "-7px 0px";
            else if (ty == 3)//err
                document.getElementById("msgBoxL").style.backgroundPosition = "-7px -108px";
        }
        function gelBox() {
            return document.getElementById("msgBox");
        }
        function gelContainer() {
            return document.getElementById("msgBoxC");
        }
        function hideBox() {
            gelBox().style.display = "none";
        }
        function showBox() {
            setPosition();
            gelBox().style.display = "block";
        }
        function setPosition() {
            lf = document.body.clientWidth / 2 - (gelBox().innerHTML.replace(/<[^>].*?>/g, "").length) * 10;
            tp = window.screen.height / 2 - 200 + document.documentElement.scrollTop;
            gelBox().style.left = lf + "px";
            gelBox().style.top = tp + "px";
        }
        function preloadImg() {
            var Arrimg = new Array();
            if (typeof (arguments[0]) == "string") Arrimg[0] = arguments[0];
            if (typeof (arguments[0]) == "object") {
                for (var i = 0; i < arguments[0].length; i++) {
                    Arrimg[i] = arguments[0][i];
                }
            }
            var img = new Array()
            for (var i = 0; i < Arrimg.length; i++) {
                img[i] = new Image();
                img[i].src = Arrimg[i];
            }
        }
        function getPos(eid) {var target = document.getElementById(eid);var left = 0, top = 0;
            do {left += target.offsetLeft || 0;top += target.offsetTop || 0;target = target.offsetParent;} while (target);
            return {left: left,top: top}
        }
        readyMsgBox();
    }
    View Code

    还有两个图片就是这两个文件,放在一个文件下面 ,用到msgbox的时候把路径添加进去就ok了。

    因为我的数据传输都是json格式所以在ui层我直接添加了一个ajaxobj.cs实体类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Ajax.UI
    {
        public class Ajaxobj
        {
            private string status;
    
            /// <summary>
            /// 状态
            /// </summary>
            public string Status
            {
                get { return status; }
                set { status = value; }
            }
    
            private string msg;
            /// <summary>
            /// 提示
            /// </summary>
            public string Msg
            {
                get { return msg; }
                set { msg = value; }
            }
            private object data;
            /// <summary>
            /// 数据
            /// </summary>
            public object Data
            {
                get { return data; }
                set { data = value; }
            }
            private string url;
            /// <summary>
            /// 地址
            /// </summary>
            public string Url
            {
                get { return url; }
                set { url = value; }
            }
        }
        public enum Estatus {
            sucess=200,
            error=500
        }
    }
    View Code

    中间有个枚举,是用来判断正确还是错误的..

    因为我是用的简单三层就没有下common层,所以在ui层我田间了一个转换序列化json格式的kiss.cs类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Ajax.UI
    {
        public static class kiss
        {
            /// <summary>
            /// json序列化
            /// </summary>
            /// <param name="model"></param>
            /// <returns></returns>
            public static string GetJson(object model) {
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                return js.Serialize(model);
            }
        }
    }
    View Code

    大体的框架就这些,这些东西我没有怎么去做优化,主要是实现功能 

    所以想现在上getlist.aspx动态页面的代码,都是用jquery异步请求一般处理程序,有些的不好的地方,希望大家能指出来,我好进行改进,还有一个我没有写样式,就连简单的边框也没有增加。哎,说多了,真的是泪,本来想前两天就把这个东西总结出来的,可是元旦事多,没有办法,只要今天来把它写完,上传,然后出去看人,希望不要有踩踏事件,昨天出去了下,从地铁出来走了半个小时,坐朋友车去了一趟小蛮腰,啥也没有干,感受了下,堵车的滋味,哎...说多了都是泪.另一个朋友说开个车去爬山,堵在半路上,上也不是下也不是,可恶的单行道...呵呵,在这里希望大家开开心心过个节,2014年对我来说真的太悲催了,主要是太菜了...都是泪呀.又闲扯了这么多鬼话.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="getlist.aspx.cs" Inherits="Ajax.UI.getlist" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <script src="js/jquery-1.9.1.js"></script>
        <script src="js/msgBox.js"></script>
        <script src="js/AjaxHelper.js"></script>
        <title></title>
        <style>
            /*设置编辑的样式和绝对定位 和透明度*/
            #edit {
            display:none;
            position:absolute;
            background-color: #878585;
            height:100%;
            100%;
            opacity:0.6;
            }
        </style>
        <script>
            var msg;
          
            
            $(function () {
                // //实例化js弹出对话框,里面存放图片的位置
                msg = new MsgBox({ imghref: "/js/imgs/" });
                //执行ajaxhelper.js文件发出异步请求
                ajaxHelper.ajaxGet("getdata.ashx?type=getdata", function (jsonobj) {
                    //判断jsonobj状态
                    if (jsonobj.Status == "error") {
                        //弹出msgbox的对话框
                       msg.showMsgErr(jsonobj.Msg);
                    } else {
                        //hide();
                        //弹出msgbox的对话框
                        MarkOpt(jsonobj.Data);
                    }
                })
                $("#btedit").click(function () {
                    //获取表单类的文本值
                    var parms = $("#f1").serialize();
                    //判断cid是否为空,为空做新增操作,不为空做编辑操作
                    if ($("#cid").val() == "") {                 
                        //异步post请求新增
                        ajaxHelper.ajaxPost("getdata.ashx?type=add", parms, function (jsonobj) {
                            if (jsonobj.Status == "error") {
                                msg.showMsgErr(jsonobj.Msg)
                            } else {
                                msg.showMsgOk(jsonobj.Msg, function () {
                                    window.location = window.location;
                                })
                            }
                        })
                    } else {
                        //异步post请求编辑操作
                        ajaxHelper.ajaxPost("getdata.ashx?type=btedit", parms, function (jsonobj) {
                            if (jsonobj.Status == "error") {
                                msg.showMsgErr(jsonobj.Msg);
                            } else {
                                msg.showMsgOk(jsonobj.Msg, function () {
                                    //刷新当前列表页面  window.location.reload();
                                    window.location = window.location;
    
                                })
                            }
                        })
                    }
                })
                //打开新增面板
                $("#add").click(function () {
                    //加载新增框
                    $("#edit").show().css("top", 200).css("left", 0);
                    //文本框里面的内容清空
                    $("#cid").val("");
                    $("#idnane").val("");
                    $("#grade").val("");
                    $("#class").val("");
                    $("#sex").val("");
                    $("#age").val("");
                    $("#time").val("");
                })
            })
           
            //获取jsonajax的json.data数据转换成td
            function MarkOpt(data) {
                //获取table 设置的id =tb 的dom元素
                var table = document.getElementById("tb");
                //遍历data数据 生成行和列  填充数据
                for (var i = 0; i < data.length; i++) {
                    //创建tr
                    var row = table.insertRow(-1);
                    //创建tr行中单元格td
                    row.insertCell(-1).innerHTML = data[i].SM_id;
                    row.insertCell(-1).innerHTML = data[i].SM_name;
                    row.insertCell(-1).innerHTML = data[i].SM_Grade;
                    row.insertCell(-1).innerHTML = data[i].SM_Classes;
                    row.insertCell(-1).innerHTML = data[i].SM_Gender;
                    row.insertCell(-1).innerHTML = data[i].SM_Age;
                    row.insertCell(-1).innerHTML = fmtdt(data[i].SM_OutTime);
                    row.insertCell(-1).innerHTML = "<a href='javascript:void(0)' onclick='Del("+data[i].SM_id+",this)' >删除</a>|<a href='javascript:void(0)' onclick='Edit("+data[i].SM_id+")' >编辑</a>";
                }
            }
            function Del(id, t) {
                //弹出对话框问是否删除
                if (confirm("确定要删除?") == false) {
                    return;
                }
                //调用ajaxhelper的js脚本 发送异步请求 交给一般处理程序处理
                ajaxHelper.ajaxGet("getdata.ashx?type=del&id=" + id, function (jsonajax) {
                    //判断jsonajax状态的值
                    if (jsonajax.Status == "error") {
                        //利用msgbox对话框弹出窗口
                        msg.showMsgErr(jsonajax.Msg);
                       
                    }
                    else {
                        //利用msgbox对话框弹出窗口
                        msg.showMsgOk(jsonajax.Msg, function () {
                            //删除td $(t)=this 表示当前行
                            $(t).parent().parent().remove();
                        })
                     
                    }
                })
            }
            //编辑的方法给文本框赋值
            function Edit(id) {
                //打开隐藏面板
                $("#edit").show().css("top", 200).css("left", 0);
                //异步请求
                ajaxHelper.ajaxGet("getdata.ashx?type=getedit&id=" + id, function (jsonobj) {
                    //判断请求是否正确
                    if (jsonobj.Status == "error") {
                        //弹出错误提示
                        msg.showMsgErr(jsonobj.Msg);
                    }
                    else {
                        //给文本框赋值
                        $("#cid").val(jsonobj.Data[0].SM_id);
                        $("#idnane").val(jsonobj.Data[0].SM_name);
                        $("#grade").val(jsonobj.Data[0].SM_Grade);
                        $("#class").val(jsonobj.Data[0].SM_Classes);
                        $("#sex").val(jsonobj.Data[0].SM_Gender);
                        $("#age").val(jsonobj.Data[0].SM_Age);
                        $("#time").val(fmtdt(jsonobj.Data[0].SM_OutTime));
    
                    }
                })
            }
          
            
     
        </script>
        <script type="text/javascript">
            //负责格式化json返回的特殊日期格式为 yyyy-mm-dd hh:mm:ss
            function fmtdt(cellval) {
                var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
                var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                return date.getFullYear() + "-" + month + "-" + currentDate + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
            }
            //关闭新增或者编辑面板
            function noshow() {
                $("#edit").hide();
            }
           
        </script>
        
    </head>
    <body>
        <form id="form1" runat="server" >
        <table id="tb">
            <tr>
                <th>id</th>
                <th>姓名</th>
                <th>班级</th>
                <th>年级</th>
                <th>性别</th>
                <th>年龄</th>
                <th>时间</th>
                <th>操作</th>
            </tr>    
        </table>
            <input type="button" value="新增" id="add"  />
        </form>
        <div id="edit">
            <form id="f1">
                <input type ="hidden" id="cid"  name="cid" value ="1" />
                <table id="tb1" class="tb2">
              
                     <tr>
                        <th>姓名</th>
                        <td><input type="text" id="idnane" name="name" value="2" /></td>
                    </tr>
                     <tr>
                        <th>班级</th>
                        <td><input type="text" id="grade" name="grade" value="3" /></td>
                    </tr>
                     <tr>
                        <th>年级</th>
                        <td><input type="text" id="class" name="class" value="4" /></td>
                    </tr>
                      <tr>
                        <th>性别</th>
                        <td><input type="text" id="sex" name="sex" value="5" /></td>
                    </tr>
                        <tr>
                        <th>年龄</th>
                        <td><input type="text" id="age" name="age" value="6" /></td>
                    </tr
                     <tr>
                        <th>时间</th>
                        <td><input type="text" id="time" name="time" value="7" /></td>
                    </tr>
                    <tr>
                        <td>
                            <input type="button" value="提交" id="btedit" />
                            <input type="button" value="关闭" onclick="noshow();" />
                        </td>
                    </tr>
                </table>
             
            </form>
        </div>
    </body>
    </html>
    View Code

    这个里面大多数我都做了注视,希望大家看的明白,还有我的新增和编辑是一个面板所以会有一个判断

    里面有个好用的jquery时间转换.可以作为资源库去使用.希望大家能直接调用就好了.

    一般处理程序的代码 getdata.ashx

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Ajax.UI
    {
        using Ajax.Model;
        using Ajax.BLL;
        /// <summary>
        /// getdata 的摘要说明
        /// </summary>
        public class getdata : IHttpHandler
        {
            Ajax.BLL.AjaxSM_Class asc = new AjaxSM_Class();
            Ajax.Model.SM_Class sc = new SM_Class();
            Ajaxobj obj = new Ajaxobj();
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                string strtype = context.Request.QueryString["type"];
                switch (strtype)
                {
                    case "getdata":
                        getlist();
                        break;
                    case "del":
                        Del();
                        break;
                    case "getedit":
                        getedit();
                        break;
                    case"btedit":
                        btedit();
                        break;
                    case"add":
                        add();
                        break;
                    default:
                        break;
                }
              
            }
            /// <summary>
            /// 新增
            /// </summary>
            private void add()
            {
                try
                {
                    string id = HttpContext.Current.Request.Form["cid"];
                    postMethod(id);
                    int i = asc.Add(sc);
                    if (i > 0)
                    {
                        obj.Msg = "新增成功";
                        obj.Status = Estatus.sucess.ToString();
                        HttpContext.Current.Response.Write(kiss.GetJson(obj));
                    }
                }
                catch (Exception ex)
                {
    
                    WriteError(ex);
                }
             
    
            }
            /// <summary>
            /// 编辑数据
            /// </summary>
            private void btedit()
            {
                try
                {
                    string id = HttpContext.Current.Request.Form["cid"];
                    postMethod(id);
    
                  int i=asc.Update(sc);
                  if (i>0)
                  {
                      obj.Msg = "修改成功成功";
                      obj.Status = Estatus.sucess.ToString();
                      HttpContext.Current.Response.Write(kiss.GetJson(obj));
                  }
    
                }
                catch (Exception ex)
                {
    
                    WriteError(ex);
                }
               
            }
    
            //获取post传递过来的数据
            private void postMethod(string id)
            {
                if (!string.IsNullOrEmpty(id))
                {
                    sc.SM_id = int.Parse(id);
                }
                //string id = HttpContext.Current.Request.Form["cid"];
                string name = HttpContext.Current.Request.Form["name"];
                string classes = HttpContext.Current.Request.Form["class"];
                string sex = HttpContext.Current.Request.Form["sex"];
                string age = HttpContext.Current.Request.Form["age"];
                string time = HttpContext.Current.Request.Form["time"];
                string grade = HttpContext.Current.Request.Form["grade"];
    
               
                sc.SM_name = name;
                sc.SM_Grade = grade;
                sc.SM_Classes = classes;
                sc.SM_Gender = sex;
                sc.SM_Age = int.Parse(age);
                sc.SM_OutTime = DateTime.Parse(time);
                sc.SM_Istf = false;
            }
            /// <summary>
            /// 获取一条数据
            /// </summary>
            private void getedit()
            {
                try
                {
                    string id = HttpContext.Current.Request.QueryString["id"];
                    List<SM_Class> list = asc.GetList(int.Parse(id));
                    if (list.Count>0)
                    {
                        obj.Data = list;
                        obj.Status = Estatus.sucess.ToString();
                        obj.Msg = "获取数据成功";
    
                        HttpContext.Current.Response.Write(kiss.GetJson(obj));
                    }
                }
                catch (Exception ex)
                {
    
                    WriteError(ex);
                }
               
            }
            /// <summary>
            /// 删除
            /// </summary>
            private void Del()
            {
                try
                {
                   string strid= HttpContext.Current.Request.QueryString["id"];
                    int id=asc.Delete(int.Parse(strid));
                    if (id>0)
                    {
                        obj.Status = Estatus.sucess.ToString();
                        obj.Msg = "数据删除成功";
                        HttpContext.Current.Response.Write(kiss.GetJson(obj));
                    }
                }
                catch (Exception ex)
                {
                  WriteError(ex);
                }
            }
            /// <summary>
            /// 获取数据
            /// </summary>
            private void getlist()
            {
                try
                {
                    List<SM_Class> List = asc.GetList();
                    if (List.Count > 0)
                    {
                        //表示成功
                        obj.Status = Estatus.sucess.ToString();
                        obj.Msg = "获取数据成功";
                        obj.Data = List;
                        HttpContext.Current.Response.Write(kiss.GetJson(obj));
                    }
                }
                catch (Exception ex)
                {
                    WriteError(ex);
                }
             
            }
    
            private void WriteError(Exception ex)
            {
                obj.Status = Estatus.error.ToString();
                obj.Msg = ex.Message;
                HttpContext.Current.Response.Write(kiss.GetJson(obj));
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    View Code
  • 相关阅读:
    在 SVG 中添加交互性
    大型Web2.0站点构建技术初探 (转)
    鼠标右键右键菜单
    用SVG技术实现动态图形输出的嵌入式Web服务
    使用脚本动态操作 SVG 文档
    GDI+技术的坐标解决方案
    一个项目的粗略流程
    xml矢量图:svg的viewBox和vml的coordsize决定的虚坐标系简说
    用VML画图(一些基本的矢量图)
    列出本地可用字体
  • 原文地址:https://www.cnblogs.com/fleas/p/4198384.html
Copyright © 2020-2023  润新知