使用ajax 无刷新对页面数据的增删改查

     这个题目让我耿耿于怀很久,曾经的一次机试题.当初是纯javascript 写的ajax。当时全部都写好了.怎奈一直返回400错误.我也知道400是找不到url地址的问题.在同级目录下.我试过好几种方式.都一样结果.最后面试夭折.人家要的是结果.....

    不废话.先看效果图.简单的增删改查.

使用ajax 无刷新对页面数据的增删改查_第1张图片

 

 1.添加.ashx文件 根据参数进行增删改查操作.

  代码如下:

 

View Code
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string model = context.Request["model"] as string;
            switch (model)
            {
                case "Insert":
                    string ID = context.Request["ID"] as string;
                    string Name = context.Request["Name"] as string;
                    string Sex = context.Request["Sex"] as string;
                    string BirthDay = context.Request["BirthDay"] as string;
                    int isOk=Insert(ID, Name, Sex, BirthDay);
                    context.Response.Write(isOk);
                    break;
                case "Delete":
                    string strID = context.Request["ID"] as string;
                    int SID = 0;
                    if (int.TryParse(strID, out SID)) { SID = int.Parse(strID); }
                    int isOK = Delete(SID);
                    context.Response.Write(isOK);
                    break;
                case "Update":
                    string UID = context.Request["ID"] as string;
                    string UName = context.Request["Name"] as string;
                    string USex = context.Request["Sex"] as string;
                    string UBirthDay = context.Request["BirthDay"] as string;
                    int sID = 0;
                    if (int.TryParse(UID, out sID)) { sID = int.Parse(UID); }
                    int isdelOk = Update(sID, UName, USex, UBirthDay);
                    context.Response.Write(isdelOk);
                    break;
                case "GetJson":
                    context.Response.Write(GetJson());
                    break;
            }
        }

        #region 增删改查

        /// <summary>
        /// 取得内存数据
        /// </summary>
        public DataTable GetDataSoure
        {
            get
            {
                DataTable dt = null;
               
                if (HttpContext.Current.Session["ajaxTable"] != null)
                {
                     dt = (DataTable)HttpContext.Current.Session["ajaxTable"];
                    if (dt == null)
                    {
                        dt = new DataTable();
                        dt.Columns.Add("ID");
                        dt.Columns.Add("Name");
                        dt.Columns.Add("Sex");
                        dt.Columns.Add("BirthDay");
                    }
                }
                else
                {
                    dt = new DataTable();
                    dt.Columns.Add("ID");
                    dt.Columns.Add("Name");
                    dt.Columns.Add("Sex");
                    dt.Columns.Add("BirthDay");
                }
                return dt;
            }
            set
            {
                HttpContext.Current.Session["ajaxTable"] = value;
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Name"></param>
        /// <param name="Sex"></param>
        /// <param name="BirthDay"></param>
        /// <returns></returns>
        public int Insert(string ID,string Name,string Sex,string BirthDay)
        {
            DataTable dt = GetDataSoure;
            DataRow row=dt.NewRow();
            row["ID"] = ID;
            row["Name"] = Name;
            row["Sex"] = Sex;
            row["BirthDay"] = BirthDay;
            dt.Rows.Add(row);
            GetDataSoure = dt;
            return 1;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int Delete(int ID)
        {
            DataTable dt = GetDataSoure;
            dt.Rows.RemoveAt(ID);
            GetDataSoure = dt;
            return 1;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Name"></param>
        /// <param name="Sex"></param>
        /// <param name="BirthDay"></param>
        /// <returns></returns>
        public int Update(int ID, string Name, string Sex, string BirthDay)
        {
            DataTable dt = GetDataSoure;
            dt.Rows.RemoveAt(ID-1);
            DataRow row = dt.NewRow();
            row["ID"] = ID;
            row["Name"] = Name;
            row["Sex"] = Sex;
            row["BirthDay"] = BirthDay;
            dt.Rows.Add(row);
            GetDataSoure = dt;
            return 1;

        }

        #endregion

        /// <summary>
        /// 转化为json 格式
        /// </summary>
        /// <returns></returns>
        public string GetJson()
        {
            StringBuilder json= new StringBuilder();
            DataTable dt = GetDataSoure;
            json.Append("[");
            foreach (DataRow row in dt.Rows)
            {
                json.Append("{");
                json.AppendFormat("ID:{0},",row["ID"].ToString());
                json.AppendFormat("Name:'{0}',", row["Name"].ToString());
                json.AppendFormat("Sex:'{0}',", row["Sex"].ToString());
                json.AppendFormat("BirthDay:'{0}'", row["BirthDay"].ToString());
                json.Append("},");
            }
            json.Append("]");
            return json.ToString().Remove(json.ToString().LastIndexOf(","), 1);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

 2.aspx页面的读取,增,删,改,查Jquery 代码

 

<script type="text/javascript" language="javascript">
//取得json 数据并绑定到html
function GetTable(){
var Json="";
$.ajax({
type:"POST",
url:"ajax.ashx",
async:false,
data:{model:"GetJson"},
success:function(msg){
Json=msg;
},
Error:function(){alert('');}

});
var htmltable="<table width='500px' border='1' class='style1'>";
htmltable+="<tr>";
htmltable+="<td>编号ID</td>";
htmltable+="<td>名称</td>";
htmltable+="<td>性别</td>";
htmltable+="<td>生日</td>";
htmltable+="</tr>";
$.each(eval(Json),function(i, n) {
htmltable+="<tr>";
htmltable+="<td>"+n.ID+"</td>";
htmltable+="<td>"+n.Name+"</td>";
htmltable+="<td>"+n.Sex+"</td>";
htmltable+="<td>"+n.BirthDay+"</td>";
htmltable+="</tr>";
})
htmltable+="</table>";
$("#ajaxtable").html(htmltable);
}
//异步插入的方法
function Insert(txtID,txtName,txtSex,txtBirthDay){
var Json="";
$.ajax({
type:"POST",
url:"ajax.ashx",
async:false,
data:{model:"Insert",ID:txtID,Name:txtName,Sex:txtSex,BirthDay:txtBirthDay},
success:function(msg){
Json=msg;
},
Error:function(){alert('');}
});
if(Json=="1")
{
GetTable();
}
}

function getajax()
{

var txtID= $("#txtID").val();
var txtName=$("#txtName").val();
var txtSex=$("#txtSex").val();
var txtBirthDay=$("#txtBirthDay").val();
Insert(txtID,txtName,txtSex,txtBirthDay);
}
//修改的方法
function Update(txtID,txtName,txtSex,txtBirthDay)
{
var Json="";
$.ajax({
type:"POST",
url:"ajax.ashx",
async:false,
data:{model:"Update",ID:txtID,Name:txtName,Sex:txtSex,BirthDay:txtBirthDay},
success:function(msg){
Json=msg;
},
Error:function(){alert('');}

});
if(Json=="1")
{
GetTable();
}
}

function getajaxByUpdate()
{
var txtID= $("#txtID").val();
var txtName=$("#txtName").val();
var txtSex=$("#txtSex").val();
var txtBirthDay=$("#txtBirthDay").val();
Update(txtID,txtName,txtSex,txtBirthDay);
}
//删除的方法
function Delete(txtID)
{
var Json="";
$.ajax({
type:"POST",
url:"ajax.ashx",
async:false,
data:{model:"Delete",ID:txtID},
success:function(msg){
Json=msg;
},
Error:function(){alert('');}

});
if(Json=="1")
{
GetTable();
}
}
function deleteajax()
{
var txtID= $("#txtID").val();
Delete(txtID);
}
</script>

 

 3.在body 页面添加html 标记

View Code
  <input id="txtID" value="" type="text" />
    <input id="txtName" value="" type="text" />
    <input id="txtSex" value="" type="text" />
    <input id="txtBirthDay" value="" type="text" />
    <input id="btnSubmit" type="button" value="提交" onclick="getajax();" />
    <input id="btnDelete" type="button" value="删除" onclick="deleteajax();" />
    <input id="btnUpdate" type="button" value="修改" onclick="getajaxByUpdate();" />
    <div id="ajaxtable">
      
    </div>

 

你可能感兴趣的:(Ajax)