你的位置:首页 > Java教程

[Java教程]数往知来 AJAX Ajax增删改查十九


=================================================客户端================================================

<script type="text/javascript">    window.onload = function () {      ShowList();      document.getElementById('btnAdd').onclick = InsertLobin;    }    function ShowList() {      var xhr = createXhr();      xhr.open("get", "LobinTable.ashx?type=s", true);      xhr.setRequestHeader("If-Modified-Since", "0");      xhr.onreadystatechange = function () {        if (xhr.readyState == 4) {          if (xhr.status == 200) {            var json = xhr.responseText;            var res = eval("(" + json + ")");            var tbl = document.getElementById("tblShow");            for (var i = 0; i < res.length; i++) {              var name = res[i].Loginname;              var time = ChangeDateFormat(res[i].LoginTime);              var row = tbl.insertRow(-1); //在table下创建一个新行,并插入到原有行的后面              var cellId = row.insertCell(-1); //在行里面创建新列              cellId.innerHTML = res[i].Id;              var cellName = row.insertCell(-1);              cellName.innerHTML = name;              var cellTime = row.insertCell(-1);              cellTime.innerHTML = time;              var cellDel = row.insertCell(-1);              cellDel.innerHTML = "<a href='javascript:Del(" + res[i].Id + ")'>删除</a>"              var cellAdd = row.insertCell(-1);              cellAdd.innerHTML = "<a href='javascript:Add()'>添加</a>";              var cellUpdate = row.insertCell(-1);              cellUpdate.innerHTML = "<a href='javascript:UpdateShow("+res[i].Id+")' >修改</a>";            }          }        }      }      xhr.send(null);    }    //显示修改的内容,定义一个全局变量把修改的id保存起来用于后面提交修改    var cid;    //点击修改    function UpdateShow(id) {    //当点击修改的时候,把层显示出来      document.getElementById('dv1').style.display = "block";      document.getElementById('btnAdd').value="修改";//把提交按钮的文本改变成“修改”      cid = id;//把选中行的id赋给一个全局变量,后面提交修改的函数里可以访问到这个id      //获得table      var tbl = document.getElementById('tblShow');      for (var i = 0; i < tbl.rows.length; i++) {        if (tbl.rows[i].childNodes[0].innerHTML == id) {//找到表格里的id和要修改的id相同的一行          document.getElementById('txtName').value = tbl.rows[i].childNodes[1].innerHTML;//把选中行的数据添加到层里面的文本框里          document.getElementById('txtPwd').value = tbl.rows[i].childNodes[2].innerHTML;          break;        }       }    }    //添加数据    var xhr = createXhr(); //创建一个Http//当点击提交按钮的时候触发    function InsertLobin() {      var btnText = document.getElementById('btnAdd').value;//获得提交按钮的文本      var txtName = document.getElementById('txtName').value;//获得用户名文本框里的内容      var txtPwd = document.getElementById('txtPwd').value;//获得密码文本框里的内容      var parameter;//要向服务器提交的参数      var type;//要做的操作,添加或修改      if (btnText == "添加") {//判断提交按钮上的文本        type = "i";//告诉服务端要做添加操作        parameter = "txtName=" + txtName + "&txtPwd=" + txtPwd + ""; //添加操作的参数      } else if (btnText == "修改") {        type = "u";        parameter = "txtName="+txtName+"&txtPwd="+txtPwd+"&id="+cid+"";//构建修改的参数    }      //调用Ajax操作      AjaxHandle(type, parameter);    }    //调用Ajax    function AjaxHandle(type,parameter) {      xhr.open("post", "LobinTable.ashx?type="+type+"", true);      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");      xhr.onreadystatechange = function () {        if (xhr.readyState == 4) {          if (xhr.status == 200) {            var json = xhr.responseText;            switch (json) {              case "1":                alert('操作成功!');                var tbl = document.getElementById('tblShow');                for (var i = 1; i < tbl.rows.length; i++) {//清空列表                  tbl.deleteRow(i);                }                document.getElementById('dv1').setAttribute('style', 'display:none');                document.getElementById('txtName').value = "";                document.getElementById('txtPwd').value = "";                ShowList();                break;              case "0":                alert('操作失败!');                break;              default:                alert('出现错误!');                break;            }          }        }      }      xhr.send(parameter);    }    //显示添加的层    function Add() {      document.getElementById('btnAdd').value = "添加";      document.getElementById('txtName').value = "";      document.getElementById('txtPwd').value = "";      document.getElementById('dv1').setAttribute('style', 'display:block');    }    //执行删除    function Del(id) {      var xhr = createXhr();      xhr.open("get", "LobinTable.ashx?type=d&id=" + id, true);      xhr.setRequestHeader("If-Modified-Since", "0");      xhr.onreadystatechange = function () {        if (xhr.readyState == 4) {          if (xhr.status == 200) {            var json = xhr.responseText;            var res = eval("(" + json + ")");            switch (res.action) {              case 1:                alert("删除成功!");                DelRow(id);                break;              case 0:                alert("删除失败!");                break;              default:                break;            }          }        }      }      xhr.send(null);    }    //删除前台页面的行    function DelRow(id) {      var tbl = document.getElementById('tblShow'); //获取表里的所有行      for (var i = 0; i < tbl.rows.length; i++) {        if (tbl.rows[i].childNodes[0].innerHTML == id.toString()) {          tbl.deleteRow(i);          break;        }      }    }    ///Date(1326505492000)/---对序列化后的日期进行转换.    function ChangeDateFormat(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;    }  </script>

=================================================服务端===========================================================================

MyName.BLL.LobinTableBLL ltb = new LobinTableBLL();  public void ProcessRequest (HttpContext context) {    context.Response.ContentType = "text/plain";    string type=context .Request .Params ["type"];    switch (type)    {      case "s":        GetAllData(context);        break;      case "d":        Del(context);        break;      case "u":        Update(context);        break;      case "i":        InsertData(context);        break;      default:        break;    }  }  /// <summary>  /// 修改更新数据  /// </summary>  /// <param name="context"></param>  /// <param name="id"></param>  protected void Update(HttpContext context)  {    MyName.Model. LobinTable lt = new MyName.Model. LobinTable();    lt.Id = Convert.ToInt32(context.Request.Form["id"]);    lt.Loginname=context.Request.Form["txtName"];    lt.LoginPwd=context.Request.Form["txtPwd"];    if (ltb.UpdateLobinTable(lt))    {      context.Response.Write("1");    }    else    {      context.Response.Write("0");    }  }  /// <summary>  /// 添加  /// </summary>  /// <param name="context"></param>  protected void InsertData(HttpContext context)  {    MyName.Model.LobinTable lt=new MyName.Model.LobinTable ();    lt.Loginname=context.Request.Form["txtName"];    lt.LoginPwd=context.Request.Form["txtPwd"];    if(ltb.AddLobinTable(lt))    {      context.Response.Write("1");    }    else    {      context.Response.Write("0");    }  }  /// <summary>  /// 删除  /// </summary>  /// <param name="context"></param>  protected void Del( HttpContext context)  {    int id = Convert.ToInt32(context .Request.QueryString["id"]);    if (ltb.DelLobinTable(id))    {      context.Response.Write("{'action':1}");    }    else    {      context.Response.Write("{'action':0}");    }  }  /// <summary>  /// 获取所有数据  /// </summary>  /// <param name="context"></param>  private void GetAllData(HttpContext context)  {    List<MyName.Model. LobinTable> list = ltb.GetAllLobinTable();    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();    string res = js.Serialize(list);    context.Response.Write(res);  }  public bool IsReusable {    get {      return false;    }  }}