AJAX简单的数据增删改与分页应用
运行截图:
PageBar.js:
/*
* 说明:
* 整体思想,1.第一页时不显示:首页,上一页,
* 2.最后一页时不显示:下一页,尾页
* 3.中间有 5 页导航,
* 若:3.1.(总页数<5),就显示多少,
* 3.2.(总页数>5),点击页码值 <=3 背景为灰色还在那个位置,
* 点击页码值 >3 背景为灰色的始终在中间,
* 点击页码值 为最后三个,背景为灰色的还在那个位置
* 4.后面追加一个跳转项
* 5.显示不显示一共多少页,纠结中......
*/
//添加实用集
/// <reference path="Utility.js" /> //总页数:要求对象请求一次更新一次
var pageCount = false;
////请求页面值
//var pageIndex = false;
//页码阵列点击函数名
var FUN = false;
//表名称标识
var TBLNAME = false; //页码条容器
function pageNavigatorPanel() {
var pnp = GetObject(arguments[0]);
//预留样式:
return pnp;
}; //创建跳转标签
function PageGoto() {
return PageTemplate("跳转", "page", "pGoto", arguments);
}; //创建尾页标签
function PageTrailer() {
return PageTemplate("尾页", "page", "pTrailer", arguments);
}; //创建下一页标签
function PageNext() {
return PageTemplate("下一页", "page", "pNext", arguments);
}; //创建上一页标签
function PagePrevious() {
return PageTemplate("上一页", "page", "pPrevious", arguments);
}; //创建首页标签
function PageFirst() {
return PageTemplate("首页", "page", "pFirst", arguments);
}; //创建页码阵列 元素id="Nav"+tit 某阵列中的元素被点击之后为其 class 添加 pageB 样式
function PageNavigatorItem(tit) {
return PageTemplate(tit, "page", "Nav" + TBLNAME + tit, arguments);
}; //创建标签母版 如需要style在外部重新定义
function PageTemplate(tit, cla, idn, args) {
var pTemplate = document.createElement("a");
pTemplate.title = tit;
pTemplate.className = cla;
pTemplate.id = idn;
//pTemplate.style = sty;
pTemplate.innerHTML = tit;
//根据 Request("get", "SList.ashx?pi=" + arguments[0] + "&name=" + arguments[1], 。。。。请求条件只要两个参数即可。
var hrf = "javascript:" + FUN + "(";
var arg3 = arguments[3];
if (arg3 != null) {// && arg3.length > 1) {
for (var i = 0; i < 1; i++) {
hrf += arg3[i] + ",\"";
}
//hrf = hrf.substr(0, hrf.length - 1);
hrf += TBLNAME + "\"";
}
hrf += ");";
pTemplate.href = hrf;
return pTemplate;
};
//清空PageBar
function EmptyPageBar() {
GetObject(arguments[0]).innerHTML ="";
};
//根据请求页码显示分页条.
function Paging(panelId, pageindex, funNavigateOnClickName, tblName) {
EmptyPageBar(panelId);
FUN = funNavigateOnClickName;
TBLNAME = tblName;
var pnp = pageNavigatorPanel(panelId);
if (pageCount == 0) {//不足一页:显示第一页
pnp.appendChild(PageNavigatorItem(1, 1));
}
else {
//1.首页显示条件
if (pageCount > 5 && pageindex > 3) {//若第一页不再阵列中就显示:
pnp.appendChild(PageFirst(1));//首页
}
//2.上一页显示条件
if (pageindex != 1) {//若不是第一页就显示:
pnp.appendChild(PagePrevious(pageindex - 1));//上一页
}
//3.页码条阵列显示
if (pageCount < 6) {//5页之内:样式点击那个哪个背景为灰色。
for (var i = 1; i <= pageCount; i++) {//添加和pageCount相等的页码条阵列
pnp.appendChild(PageNavigatorItem(i, pageindex));
}
} else {//大于5页(2 < pageindex < pageCount-1)的样式:灰色背景
//3.1前三个跟着走
if (pageindex <= 3) {
for (var i = 1; i < 6; i++) {
pnp.appendChild(PageNavigatorItem(i, pageindex));
}
}
//3.2一直在中间
if (3 < pageindex && pageindex < pageCount - 2) {
for (var i = pageindex - 2; i < pageindex + 3; i++) {
pnp.appendChild(PageNavigatorItem(i, pageindex));
}
}
//3.3后三个跟着走
if (pageindex >= pageCount - 2) {
for (var i = pageCount - 4; i <= pageCount; i++) {
pnp.appendChild(PageNavigatorItem(i, pageindex));
}
}
}
//4.下一页显示条件
if (pageindex < pageCount) {//若不是最后一页就显示:
pnp.appendChild(PageNext(pageindex + 1));//下一页
}
//5.尾页显示条件(若最后一页不再阵列中)
if (pageindex < pageCount - 2) {
pnp.appendChild(PageTrailer(pageCount));//尾页
}
//为点击元素附加类样式pageB,并且禁用a标签。
var aTag = GetObject("Nav" + TBLNAME + pageindex);
aTag.className += " pageB";
aTag.removeAttribute("href");
//下面这个无效
//aTag.onclick = function () { return false; };
//增加跳转条件
if (pageCount > 18) {//页数大于18 才有显示的必要
//跳转输入框变量
var gt = ' 至第<input type="text" id="pGoto" style="border:1px solid rgb(206,206,206); width:31px;height:19px;margin:1px 0;text-align:center;" />页 ';
pnp.innerHTML += gt;
pnp.appendChild(PageGoto(parseInt(GetObject("pGoto").value)));//NaN
}
}
};
修改后更通用的
PageBar.js
/* Author:
* By Wang
*
* 说明:
* 整体思想,1.第一页时不显示:首页,上一页,
* 2.最后一页时不显示:下一页,尾页
* 3.中间有 5 页导航,
* 若:3.1.(总页数<5),就显示多少,
* 3.2.(总页数>5),点击页码值 <=3 背景为灰色还在那个位置,
* 点击页码值 >3 背景为灰色的始终在中间,
* 点击页码值 为最后三个,背景为灰色的还在那个位置
* 4.后面追加一个跳转项
* 5.显示不显示一共多少页,纠结中......
* 主函数:Paging
*/
//添加实用集
/// <reference path="Utility.js" /> //总页数:要求对象请求一次更新一次
//var pageCount = false;
////请求页面值
//var pageIndex = false;
//页码阵列点击函数名
var FUN = false;
var IDPR = "Page";
//页码条容器
function pageNavigatorPanel() {
var pnp = GetObject(arguments[0]);
//预留样式:
return pnp;
}; //创建跳转标签
function PageGoto() {
return PageTemplate("跳转", "page", IDPR + "Goto", arguments);
}; //创建尾页标签
function PageTrailer() {
return PageTemplate("尾页", "page", IDPR + "Trailer", arguments);
}; //创建下一页标签
function PageNext() {
return PageTemplate("下一页", "page", IDPR + "Next", arguments);
}; //创建上一页标签
function PagePrevious() {
return PageTemplate("上一页", "page", IDPR + "Previous", arguments);
}; //创建首页标签
function PageFirst() {
return PageTemplate("首页", "page", IDPR + "First", arguments);
}; //创建页码阵列 元素id="Nav"+tit 某阵列中的元素被点击之后为其 class 添加 pageB 样式
function PageNavigatorItem(tit) {
return PageTemplate(tit, "page", IDPR + tit, arguments);//默认有一个page样式
}; //创建标签母版: tit:显示内容,cla:样式类名,idn:id名称,args:参数
function PageTemplate(tit, cla, idn, args) {
var pTemplate = document.createElement("a");
pTemplate.title = tit;
pTemplate.className = cla;
pTemplate.id = idn;
//pTemplate.style = sty;
pTemplate.innerHTML = tit;
//点击执行的js函数
var hrf = "javascript:" + FUN + "(";
var arg3 = arguments[3];
//if (arg3 != null && arg3.length > 1) {
//for (var i = 0; i < 1; i++) {
hrf += ("'" + idn + "',");
hrf += arg3[0];
//}
//}
hrf += ");";
pTemplate.href = hrf;
return pTemplate;
};
//清空PageBar
function EmptyPageBar() {
GetObject(arguments[0]).innerHTML = "";
};
//根据请求页码显示分页条.
function Paging(panelId, pageindex, pageCount, pageTagClickFuncName) {
EmptyPageBar(panelId);
FUN = pageTagClickFuncName;
var pnp = pageNavigatorPanel(panelId);
if (pageindex == 0) {
pnp.innerHTML = "<strong color='red'>对不起,没有数据...</strong>";
return;
}
if (pageCount == 0) {//不足一页:显示第一页
pnp.appendChild(PageNavigatorItem(1));
}
else {
//1.首页显示条件
if (pageCount > 5 && pageindex > 3) {//若第一页不再阵列中就显示:
pnp.appendChild(PageFirst(1));//首页
}
//2.上一页显示条件
if (pageindex != 1) {//若不是第一页就显示:
pnp.appendChild(PagePrevious(pageindex - 1));//上一页
}
//3.页码条阵列显示
if (pageCount < 6) {//5页之内:样式点击那个哪个背景为灰色。
for (var i = 1; i <= pageCount; i++) {//添加和pageCount相等的页码条阵列
pnp.appendChild(PageNavigatorItem(i));
}
} else {//大于5页(2 < pageindex < pageCount-1)的样式:灰色背景
//3.1前三个跟着走
if (pageindex <= 3) {
for (var i = 1; i < 6; i++) {
pnp.appendChild(PageNavigatorItem(i));
}
}
//3.2一直在中间
if (3 < pageindex && pageindex < pageCount - 2) {
for (var i = pageindex - 2; i < pageindex + 3; i++) {
pnp.appendChild(PageNavigatorItem(i));
}
}
//3.3后三个跟着走
if (pageindex >= pageCount - 2) {
for (var i = pageCount - 4; i <= pageCount; i++) {
pnp.appendChild(PageNavigatorItem(i));
}
}
}
//4.下一页显示条件
if (pageindex < pageCount) {//若不是最后一页就显示:
pnp.appendChild(PageNext(pageindex + 1));//下一页
}
//5.尾页显示条件(若最后一页不再阵列中)
if (pageindex < pageCount - 2) {
pnp.appendChild(PageTrailer(pageCount));//尾页
}
//增加跳转条件
if (pageCount > 10) {//页数大于10 才有显示的必要
//跳转输入框变量
var gt = ' 至第<input type="text" id="PageGotoIndex" style="border:1px solid rgb(206,206,206); width:31px;height:19px;margin:1px 0;text-align:center;" />页 ';
pnp.innerHTML += gt;
pnp.appendChild(PageGoto(parseInt(GetObject("PageGotoIndex").value)));//NaN
}
}
//为点击元素附加类样式pageB,并且禁用a标签。
var aTag = GetObject(IDPR + pageindex);
if (typeof (aTag) != "undefined") {
aTag.className += " pageB";
aTag.removeAttribute("href");
}
//下面这个无效
//aTag.onclick = function () { return false; };
};
Utility.js
/*
* js实用工具箱
*/ //根据id获取对象:传递一个参数id
function GetObject() {
return document.getElementById(arguments[0]);
}; //创建对象
function SetObject() {
return document.createElement(arguments[0]);
}; //根据id获取对象:指示在浏览器中是否隐藏{false:"block",ture:"none"}
function Display(id, bool) {
var dis = "block";
if (bool)
dis = "none";
GetObject(id).style.display = dis;
}; //将从集合中转换出来的Json类型时间格式(/Date(308592000000)/)转换成正常格式spli="-"(year-month-day)
function GetDateFromJsonDate(jsonDate, spli) {
if (spli == null || spli == undefined)
//spli = "/";//数据插入失败
spli = "-";
// \\/Date(308592000000)\\/
// /Date(308592000000)/
var fakeDate = arguments[0];
//1.取数字转换为十进制整数
fakeDate = fakeDate.match(/\d+/);//1.推荐.保险
//fakeDate = fakeDate.replace("/", "").replace("Date(", "").replace(")", "").replace("/", "");//2.
//fakeDate = fakeDate.substring(6, fakeDate.length - 2);
//2.解析为十进制数字
var dec = parseInt(fakeDate, 10);
//3.获取date对象
var date = new Date(dec)
//4.拼接格式化
var day = date.getDate();
var mon = date.getMonth() + 1;
return date.getFullYear() + spli + (mon < 10 ? "0" + mon : mon) + spli + (day < 10 ? "0" + day : day);
}; //获取AJAX中的异步对象
function GetXHR() {
var XHR = false;
/* try {
XHR = new ActiveXObject("Msxml2.XMLHTTP"); // ie msxml3.0+
} catch (M2) {
try {
XHR = new ActiveXObject("Microsoft.XMLHTTP"); //ie msxml2.6
} catch (Mt) {
XHR = false;
}
}
if (!XHR && typeof XMLHttpRequest != 'undefined') {// Firefox, Opera 8.0+, Safari
XHR = new XMLHttpRequest();
}*/
XHR = new XMLHttpRequest();
return XHR;
}; //实现异步对象的Request请求
function Request(method, url, iscache, funNameDoResponse, funNameDoErrorBystatus, send) {
var xhr = GetXHR();
xhr.open(method, url, true);
if (method.toLowerCase() == "post") //application/x-www-form-urlencoded
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (iscache)
xhr.setRequestHeader("If-Modified-Since", "0");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//如果是值是空 json数组是null ,而不是 \"\"=""
var cont = xhr.responseText;//{\"Id\":1,\"Math\":null,\"English\":40}
//将json 字符串传入-->
funNameDoResponse(cont);
} else {
if (funNameDoErrorBystatus != null)
funNameDoErrorBystatus(xhr.status);
}
}
};
xhr.send(send);
};
PageBarStyle.css
.page {
background-color: rgba(255, 255, 255, 1.00);
text-decoration: none; /*去掉下滑线*/
color: rgb(102,102,102);
/*align-content: center;*/
font-size: 12px;
font-family: 'MS PMincho';
border: 1px solid rgb(206,206,206);
padding: 5px 8px;
margin: 1px;
} a.page:hover {
cursor: pointer;
color: rgb(0,165,97);
}
/**/
/* a[class*="pageB"]:visited {
}*/ /*MS PMincho*/
.pageB {
/*padding: 5px 8px; 重写要>=起效*/
cursor: text;
font-weight:bolder;
background-color: rgb(206,206,206);
color: rgb(255,255,255);
}
List.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>学生信息列表</title>
<link href="CSS/PageBarStyle.css" rel="stylesheet" />
<style>
.center {
position: relative;
left: 50%;
top: 50%;
} table {
margin: 20px;
} td {
text-align: center;
padding: 6px;
margin: 5px;
border: 1px solid #f00;
} p {
font-size: xx-large;
color: #0026ff;
padding: 5px;
text-align: center;
} .Add {
display: none;
position: fixed;
left: 50%;
top: 50%;
border: 1px solid #b200ff;
padding: 10px 0 0 10px;
background-color: #ff006e;
z-index: 110;
opacity: 0.8;
font-weight: 800;
} .button {
margin: 8px 10px 0 auto;
padding: 5px;
float: right;
} input[type=button] {
margin-left: 15px;
} input[type=text] {
margin: 2px;
}
</style>
<script src="JS/Utility.js"></script>
<script src="JS/PageBar.js"></script>
<script type="text/javascript">
var tblRowId = false;
var tblScore = false;
var tblStudent = false;
var Modify = false;
//辅助
function Error() {
alert("未知原因,操作失败");
Display("scoAdd", true);
Display("stuAdd", true);//
};
function CheckInput() {
//数据库表示可以为空返回 true
//if (txtName.value == "") {
// alert("请输入姓名");
// return false;
//}
//else if (txtAge.value == "") {
// alert("请输入年龄");
// return false;
//}
//else if (txtGender.value == "") {
// alert("请输入性别");
// return false;
//}
//else if (txtCID.value == "") {
// alert("请输入班级ID");
// return false;
//}
//else if (txtBirthday.value == "") {
// alert("请输入日期");
// return false;
//}
return true;
};
function Cancel() {
Modify = false;//1.
Display(arguments[0], true);
};
//End辅助
//删除操作
function DeleteCascade() {
//遍历比较id值
//var tbl = GetObject("tblSco");
var length = tblScore.rows.length;
for (var i = 0; i < length; i++) {
var ro = tblScore.rows.item(i)
if (ro.childNodes[0].innerHTML == tblRowId) {
// if (ro.id == "sco" + tblRowId) {
tblScore.deleteRow(i);
tblRowId = false;
return;
}
}
tblRowId = false;
};
function DeleteResult() {//实际情况下删除后要更新pageCount的,不然删除后,再跳转最后一页,什么都没有了,或出现错误。
if (arguments[0] == 1) {
alert("删除成功");
//界面删除stu
//var roi = GetObject("stu" + tblRowId).getAttribute("name");
//GetObject("tblStu").deleteRow(roi);
//这样删除是错误的,表的行是动态变化的,
//GetObject("tblStu").deleteRow(tblStuRowIndex);//行索引是从 0 开始的
//var tbl = GetObject("tblStu");
length = tblStudent.rows.length;
for (var i = 0; i < length; i++) {
if (tblStudent.rows.item(i).childNodes[0].innerHTML == tblRowId) {
tblStudent.deleteRow(i);
break;
}
}
DeleteCascade();
return;
}
alert("删除失败");
};
function Delete() {
if (confirm("确定要删除吗?")) {
tblRowId = arguments[0];
var send = "id=" + tblRowId;
Request("POST", "NonQuery.ashx", false, DeleteResult, null, send);
// Request("get", "NonQuery.ashx?" + send, false, DeleteResult, null, null);
}
};
//End删除操作
//添加
function AddScoResult() {
Display("scoAdd", true);//无论结果如何都关闭成绩弹出框
if (arguments[0] == 1) {
alert("添加成功");
return;
}
Error();
};
function AddStuResult() {
Display("stuAdd", true);//结果回来然后关闭弹出框
var cont = arguments[0];
if (cont >= 1) {//学生插入成功:返回@@identity :自增id identity(1,1)
InitScoAdd();
//成绩没有Check:一定会在数据库添加。
Display("scoAdd", false);
txtId.value = parseInt(cont);
//这里通过对比表格的 行数据的ID值 。。。。。更新UI
// OK(2);
return;
}
Error();
};
var txtName, txtAge, txtGender, txtCID, txtBirthday;
function InitStuAdd() {
//若输入框已经实例化了,修改后会自动有值
if (txtName == undefined || txtName == false) {
txtName = GetObject("txtName");
txtAge = GetObject("txtAge");
txtGender = GetObject("txtGender");
txtCID = GetObject("txtCID");
txtBirthday = GetObject("txtBirthday");
}
};
var txtId, txtMath, txtEnglish;
function InitScoAdd() {
if (txtId == undefined || txtId == false) {
txtId = GetObject("txtId");
txtMath = GetObject("txtMath");
txtEnglish = GetObject("txtEnglish");
}
};
function Add() {
//增加stu成功后才显示增加sco否则不显示。
Display("stuAdd", false);
//初始化输入框对象
InitStuAdd();
// OK(1);
};
//End添加
//修改
function AppendConcelButton() {
var btnCnl = document.createElement("input");
btnCnl.type = "button";
btnCnl.onclick = function () {
Cancel("scoAdd");//点击取消按钮,
};
btnCnl.value = "取消";
return btnCnl;
};
function RefreshStuUI() {
var row = GetObject(tblRowId);//存在视觉性 Bug !!!
//row.firstElementChild.innerHTML = txtId.value;
row.children.item(1).innerHTML = txtName.value;
row.childNodes[2].innerHTML = txtAge.value;
row.childNodes[3].innerHTML = txtGender.value;
row.children.item(4).innerHTML = txtCID.value;
row.childNodes[5].innerHTML = txtBirthday.value;
tblRowId = false;
};
function ModifyStuResult() {
if (arguments[0] == 1) {
alert("修改成功");
RefreshStuUI();
} else {
alert("修改失败");
}
Cancel("stuAdd");//无论成功失败都关闭。
};
function RefreshScoUI() {
var row = GetObject(tblRowId);//存在视觉性 Bug !!!
row.childNodes[1].innerHTML = txtMath.value;
row.childNodes[2].innerHTML = txtEnglish.value;
tblRowId = false;
};
function ModifyScoResult() {
if (arguments[0] == 1) {
alert("修改成功");
RefreshScoUI();
} else {
alert("修改失败");
}
Cancel("scoAdd");//无论成功失败都关闭。
};
function InitScoModify() {
InitScoAdd();
//给单元格赋值
var row = GetObject(tblRowId);
txtId.value = row.firstChild.innerHTML;
// txtId.value = row.firstElementChild.innerHTML;
txtMath.value = row.children.item(1).innerHTML;
txtEnglish.value = row.childNodes[2].innerHTML;
var ADiv = GetObject("Action");
if (ADiv.childElementCount == 1)
// ADiv.insertBefore(AppendConcelButton());
ADiv.appendChild(AppendConcelButton());
};
function InitStuModify() {
InitStuAdd();
var row = GetObject(tblRowId);
//txtId.value = row.firstElementChild.innerHTML;
txtName.value = row.children.item(1).innerHTML;
txtAge.value = row.childNodes[2].innerHTML;
txtGender.value = row.childNodes[3].innerHTML;
txtCID.value = row.children.item(4).innerHTML;
txtBirthday.value = row.childNodes[5].innerHTML;
}
function Modified() {//传递ID
tblRowId = arguments[0] + arguments[1];
if (arguments[0] == "sco") {
Display("scoAdd", false);
Modify = true;//开启修改模式,然后,两种情况下关闭:1.点击取消。2.xhr.send()之后。
InitScoModify();
} else {
//stu
Display("stuAdd", false);
Modify = true;
InitStuModify();
}
};
//End修改
//确定
function OK() {
if (arguments[0] == 1) {//stu
if (CheckInput()) {//发送数据
var send = "name=" + txtName.value + "&age=" + txtAge.value + "&gender=" + txtGender.value + "&cid=" + txtCID.value + "&birthday=" + txtBirthday.value;
if (!Modify)
Request("POST", "NonQuery.ashx", false, AddStuResult, Error, send);
else
Request("POST", "NonQuery.ashx?actionId=" + tblRowId.toString().substr(3), false, ModifyStuResult, Error, send);
}
} else {//sco
var send = "sid=" + txtId.value + "&math=" + txtMath.value + "&english=" + txtEnglish.value;
if (!Modify)
Request("POST", "NonQuery.ashx", false, AddScoResult, Error, send);
else
Request("POST", "NonQuery.ashx?actionId=" + tblRowId.toString().substr(3), false, ModifyScoResult, Error, send);//
}//看看是否进入下一步。:可以,
Modify = false;//2.
};
function RemoveRowToTable() {
var tbl = arguments[0];
var i = tbl.rows.length - 2;//为不足8行除错
if (tbl.rows.length > 3)
for (; i > 1; i--) {//5行数据 倒着删
tbl.deleteRow(i);
}
};
function InsertRowTotblSco() {
var tblScoreRow = tblScore.insertRow(arguments[0]);
//tblScoreRow.setAttribute("name", arguments[0]);
//为了对ID进行区别
tblScoreRow.id = "sco" + arguments[1]; //设置当前行的id值
//
var td0 = tblScoreRow.insertCell(-1);//这个没有提示~~(但是有这个方法)
td0.innerHTML = arguments[1];
////火狐下不兼容
//var td1 = tblScoreRow.insertBefore(document.createElement("td"));
var td1 = tblScoreRow.insertCell(-1);
td1.innerHTML = arguments[2];
//
var td2 = tblScoreRow.appendChild(document.createElement("td"));
td2.innerHTML = arguments[3];
//
var td3 = tblScoreRow.insertCell(-1);
//第一种:显示传参
td3.innerHTML = "<a href='javascript:Modified(\"sco\"," + arguments[1] + ");'>修改</a>";
};
function InsertRowTotblStu() {
var tblStudentRow = tblStudent.insertRow(arguments[0]);//arguments[0]=row的索引
//tblStudentRow.setAttribute("name", arguments[0]); tblStudentRow.id = "stu" + arguments[1];
var td0 = tblStudentRow.insertCell(-1);
td0.innerHTML = arguments[1];
var td1 = tblStudentRow.insertCell(-1);
td1.innerHTML = arguments[2];
var td2 = tblStudentRow.insertCell(-1);
td2.innerHTML = arguments[3];
var td3 = tblStudentRow.insertCell(-1);
td3.innerHTML = arguments[4];
var td4 = tblStudentRow.insertCell(-1);
td4.innerHTML = arguments[5];
var td5 = tblStudentRow.insertCell(-1);
td5.innerHTML = GetDateFromJsonDate(arguments[6]);
var td6 = tblStudentRow.insertCell(-1);
//第二种:根据表格行获取单元格值。
td6.innerHTML = "<a href='javascript:Modified(\"stu\"," + arguments[1] + ");'>修改</a> <a href='javascript:Delete(" + arguments[1] + ");'>删除</a>";
};
function JsonStrToTable() {//接受数据函数
var arr = arguments[0].split(" ");
//每次回来数据都更新页数
pageCount = parseInt(arr[1]);
var pIndex = parseInt(arr[2]);
//也可以
var json = JSON.parse(arr[0]);
//var json = eval(arguments[0]);
if (json != null) {//为防止删除后的出错
if (json != undefined) {//对eval的判断
if (json.length > 0) {
if (json[0].Name == undefined) {
RemoveRowToTable(tblScore);
//向表格里插入行
for (var i = 0; i < json.length ; i++) {
//tblScore.rows.length :自动增长的
InsertRowTotblSco(tblScore.rows.length - 1, json[i].Id, json[i].Math, json[i].English);
}
//如果在这里同时插入pageBar当然没问题,pageCount已经初始化了
//但是请求页码值无法确定。
Paging("pageBarSco", pIndex, "NavigateOnClick", "sco");
} else {
//清空不需要的数据
RemoveRowToTable(tblStudent);
for (var i = 0; i < json.length; i++) {
//{\"sId\":{\"Id\":1,\"Math\":null,\"English\":40},
// \"Id\":1,\"Name\":\"张夏槐\",
// \"Age\":9,\"Gender\":\"女\",\"CID\":2,
// \"BirthDay\":\"\\/Date(308592000000)\\/\"},
InsertRowTotblStu(tblStudent.rows.length - 1, json[i].Id, json[i].Name, json[i].Age, json[i].Gender, json[i].CID, json[i].BirthDay);
}
Paging("pageBarStu", pIndex, "NavigateOnClick", "stu");
}
}
}
}
////
//pageCount = false;
};
function RequestPageByIndexAndName() {
function cm() {
/*
var xhr = GetXHR();
//重复利用可以用 参数化
xhr.open("get", "SList.ashx?pi=" + arguments[0] + "&name=" + arguments[1], true);
//http://localhost:1030/List.aspx?pI=1 (Cache)
xhr.setRequestHeader("If-Modified-Since", "0");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//如果是值是空 json数组是null ,而不是 \"\"=""
var cont = xhr.responseText;//{\"Id\":1,\"Math\":null,\"English\":40}
//将json 字符串传入-->
JsonStrToTable(cont);
} else {
alert("数据错误。");
}
}
};
xhr.send(null);
*/
}; //Error:说明若"Error",未找到函数。
Request("get", "SList.ashx?pi=" + arguments[0] + "&name=" + arguments[1], true, JsonStrToTable, Error, null);
//如果在这里同时插入pageBar会出现问题,pageCount还没有值。
////只能用线程性接受pageCount
//var tid = setInterval(function () {
// if (pageCount != false) { // }
//}, 200);
};
//被请求页
function NavigateOnClick() {
//发送请求
var pi = arguments[0];
if (isNaN(pi))
pi = parseInt(GetObject("pGoto").value);
if (pi < 1)
pi = 1;
else if (pi > pageCount)
pi = pageCount;
RequestPageByIndexAndName(pi, arguments[1]);
};
window.onload = function () {
tblStudent = GetObject("tblStu");
tblScore = GetObject("tblSco");
RequestPageByIndexAndName(1, "sco");//动态删除后分页有Bug
RequestPageByIndexAndName(1, "stu");
////向PageBar位置输出
//pageNavigatorPanel("pageBarSco");
//pageNavigatorPanel("pageBarStu");
};
</script>
</head>
<body>
<div>
<p>学生信息列表</p>
<table cellspacing="0" id="tblSco" class="center" style="width: 620px; margin-left: -310px;">
<tr>
<td colspan="4" style="padding-bottom: 20px; border: none;">成绩表</td>
</tr>
<tr>
<td>id</td>
<td>Math</td>
<td>English</td>
<td>Edit</td>
</tr>
<!--<%--用另一种方式了--%>
<%----%> <%=sbSco==null?"":sbSco.ToString() %>-->
<tr>
<!-- <td>分页</td>-->
<td colspan="4">
<div id="pageBarSco"></div>
<!-- <a title="首页" class="page" id="pFirst" href="#" style="">首页</a>
<a title="上一页" class="page" id="pPrevious" href="#">上一页</a>
<a title="" class="page pageB" id="" href="#">8</a>
<a title="" class="page pageB" id="A5" href="#">9</a>
<a title="" class="page pageB" id="A6" href="#">10</a>
<a title="" class="page pageB" id="A7" href="#">11</a>
<a title="" class="page pageB" id="A8" href="#">12</a>
<a title="下一页" class="page" id="pNext" href="#">下一页</a>
<a title="尾页" class="page" id="pTrailer" href="#">尾页</a>
至第<input type="text" id="pGoto" style="border:1px solid rgb(206,206,206); width:31px;height:19px;margin:1px 0;text-align:center;" />页-->
</td>
<!-- <td>分页</td>-->
</tr>
</table>
<hr style="width: 57%; color: #b200ff;" />
<table cellspacing="0" id="tblStu" class="center" style="width: 760px; margin: 25px 0 0 -380px;">
<tr>
<td colspan="6" style="border: none; text-align: left; padding-left: 16px;">学生表</td>
<td style="border: none;"><a href="javascript:Add();">增加</a></td>
</tr>
<tr>
<td style="">id</td>
<td>Name</td>
<td>Age</td>
<td>Gender</td>
<td>ClassId</td>
<td>Birthday</td>
<td>Edit</td>
</tr>
<!--<%--用另一种方式了--%>
<%----%> <%=sbStu==null?"":sbStu.ToString() %>-->
<tr>
<td>分页</td>
<td colspan="5">
<div id="pageBarStu"></div>
<!-- <a title="首页" class="page" id="A1" href="#">首页</a>
<a title="上一页" class="page" id="A2" href="#">上一页</a>
<a title="下一页" class="page" id="A3" href="#">下一页</a>
<a title="尾页" class="page" id="A4" href="#">尾页</a> -->
</td>
<td>分页</td>
</tr>
</table>
</div>
<hr style="width: 70%; color: #b200ff; margin-top: 2%;" />
<p style="font-size: medium; padding: 15px 0;">主要练习异步对象,分页</p>
<!-- 有了AJAX就不用提交表单了。-->
<!-- <form method="post" action="NonQuery.ashx">-->
<div id="stuAdd" class="Add" style="width: 400px; height: 150px; margin-left: -200px; margin-top: -75px;">
姓名:<input type="text" id="txtName" />
年龄:<input type="text" id="txtAge" />
性别:<input type="text" id="txtGender" /><br />
班级ID:<input type="text" id="txtCID" /><br />
出生日期:<input type="text" id="txtBirthday" /><br />
<div class="button">
<!--不能写成 submit 不然后台得不到数据-->
<input type="button" value="确定" onclick="OK(1);" /><input type="button" value="取消" onclick=" Cancel('stuAdd');" />
</div>
</div>
<!-- </form>-->
<!--练习储存过程的@@identity
<form method="post" action="NonQuery.ashx">-->
<div id="scoAdd" class="Add" style="width: 280px; height: 126px; margin: -63px 0 0 -140px;">
id:<input type="text" id="txtId" readonly="readonly" /><br />
Math:<input type="text" id="txtMath" /><br />
English:<input type="text" id="txtEnglish" />
<div class="button" id="Action">
<!--不能写成 submit 不然后台得不到数据-->
<input type="button" value="确定" onclick="OK(2);" /><!--<input type="button" value="取消" onclick="Cancel();" />-->
</div>
</div>
<!-- </form>-->
</body>
</html>
SList.ashx
<%@ WebHandler Language="C#" Class="SList" %> using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic; public class SList : IHttpHandler
{
private Web.BLL.TransferAction action = null; private int rowCount, pageCount;
private int pageSize = , pageIndex; public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html"; //不能判断是get,post方式下取值
string pIndex = context.Request.Params["pi"];
string tblName = context.Request.QueryString["name"];
if (pIndex != null && tblName != null)
{
pageIndex = int.Parse(pIndex);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); if (tblName == "sco")//"stu"
{
List<Web.Model.MyScore> lsSco = this.GetList<Web.Model.MyScore>(out rowCount, out pageCount, pageIndex, pageSize);
//序列化为Json字符串。
context.Response.Write(jsSerializer.Serialize(lsSco));
}
else
{
List<Web.Model.MyStudent> lsStu = this.GetList<Web.Model.MyStudent>(out rowCount, out pageCount, pageIndex, pageSize);
context.Response.Write(jsSerializer.Serialize(lsStu));
}
}
//看客户端能接受到pageCount? YES//别忘了缓冲区。
//if (pageIndex > pageCount)
// pageIndex = pageCount;
context.Response.Write(" " + pageCount + " " + pageIndex);
}
public List<T> GetList<T>(out int rowCount, out int pageCount, int pageIndex, int pageSize = )
{
//T a = T() ;
List<T> lt = new List<T>();
action = new Web.BLL.TransferAction();
if (lt is List<Web.Model.MyScore>)
{
return action.GetListSco(out rowCount, out pageCount, pageIndex, pageSize) as List<T>;
}
else
{
return action.GetListStu(out rowCount, out pageCount, pageIndex, pageSize) as List<T>;
}
} }
NonQuery.ashx
<%@ WebHandler Language="C#" Class="NonQuery" %> using System;
using System.Web; public class NonQuery : IHttpHandler
{
private int result = -;
private Web.BLL.TransferAction action = null; public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
//临时变量
int tmp; DateTime dt;
Web.Model.ActionBehavior AB; //null;//枚举不是引用类型
//是否可以用到 ActionBehavior
//不能用传过来的是字符串,不是类型。
//删除(级联)
string id = context.Request.Form["id"];
// string id = context.Request.Params["id"];
// string id = context.Request.QueryString["id"];
//添加(学生)
string name = context.Request.Form["name"];
//添加(成绩)
string sid = context.Request.Form["sid"]; //修改 action=modify
string actid = context.Request.QueryString["actionId"];
AB = Web.Model.ActionBehavior.Add;
if (actid != null)
AB = Web.Model.ActionBehavior.Modify; //用一个 action 对象可以吗?:肯定不行
if (id != null)
{
action = new Web.BLL.TransferAction();
result = action.ExecuteNonQuery(Web.Model.ActionBehavior.Delete, new Web.Model.MyStudent() { Id = int.Parse(id) });
}
else if (name != null)
{
string age = context.Request.Form["age"];
string gender = context.Request.Form["gender"];
string cid = context.Request.Form["cid"];
string birthday = context.Request.Form["birthday"]; action = new Web.BLL.TransferAction();
result = action.ExecuteNonQuery<Web.Model.MyStudent>(AB,
new Web.Model.MyStudent()
{ Id = actid == null ? : int.Parse(actid),
Name = name == "" ? null : name,
Age = int.TryParse(age, out tmp) == true ? (int?)tmp : null,
Gender = (gender == "男" || gender == "女") ? (char?)char.Parse(gender) : null,
CID = int.TryParse(cid, out tmp) == true ? (int?)tmp : null,
BirthDay = DateTime.TryParse(birthday, out dt) == true ? (DateTime?)dt : null
});
}
else if (sid != null)
{
string math = context.Request.Form["math"];
string english = context.Request.Form["english"]; action = new Web.BLL.TransferAction(); result = action.ExecuteNonQuery<Web.Model.MyScore>(AB,
new Web.Model.MyScore()
{
Id = int.Parse(sid),
Math = int.TryParse(math, out tmp) == true ? (int?)tmp : null,
English = int.TryParse(english, out tmp) == true ? (int?)tmp : null
});
}
//结果返回
context.Response.Write(result);
} }
DataAction.cs
public class DataAction
{
private List<Web.Model.MyStudent> ltStu = null;
private List<Web.Model.MyScore> ltSco = null;
public DataAction()
{
ltStu = new List<Web.Model.MyStudent>();
} public List<Web.Model.MyStudent> GetListStu(out int rowCount, out int pageCount, int pageIndex, int pageSize = )
{
rowCount = pageCount = -;
//定义参数
System.Data.SqlClient.SqlParameter[] param = {new System.Data.SqlClient.SqlParameter( "@pageIndex",pageIndex),
new System.Data.SqlClient.SqlParameter("@pageSize",pageSize),
new System.Data.SqlClient.SqlParameter("@rowCount",rowCount),
new System.Data.SqlClient.SqlParameter("@pageCount",pageCount) };
//方向
param[].Direction = System.Data.ParameterDirection.Output;
param[].Direction = System.Data.ParameterDirection.Output; using (System.Data.SqlClient.SqlDataReader reader = SqlHelper.ExecuteGetPaging("pro_MyStudent", param))
{
if (reader.HasRows)
{
Web.Model.MyStudent stu = null;
ltStu = new List<Model.MyStudent>();
while (reader.Read())
{
//由于储存过程
// select * from (
// select row_number() over(order by id) as IsIdentity,* from MyStudent
// ) as tbl where tbl.IsIdentity between * and *
//增加了一列IsIdentity
stu = new Web.Model.MyStudent();
stu.Id = int.Parse(reader[].ToString());
stu.sId = this.GetScore(stu.Id);
stu.Name = reader.IsDBNull() ? null : reader[].ToString();
stu.Age = reader.IsDBNull() ? null : (int?)reader.GetInt32();
stu.Gender = reader.IsDBNull() ? null : (char?)char.Parse(reader[].ToString());
stu.CID = reader.IsDBNull() ? null : (int?)int.Parse(reader[].ToString());
stu.BirthDay = reader.IsDBNull() ? null : (DateTime?)reader.GetDateTime();
ltStu.Add(stu);
} //为什么???
//结束当前游标 (指向下一个程序集。)
if (reader.NextResult())
{
//while (reader.Read())
//{
// rowCount = int.Parse(param[2].Value.ToString());
// pageCount = Convert.ToInt32(param[3].Value);
//}
}
// object a=reader[0];
rowCount = int.Parse(param[].Value.ToString());
pageCount = Convert.ToInt32(param[].Value);
}
return ltStu;
}
} public List<Web.Model.MyScore> GetListSco(out int rowCount, out int pageCount, int pageIndex, int pageSize = )
{
rowCount = pageCount = -;
using (System.Data.DataTable dt = SqlHelper.ExecuteGetPaging("pro_MyScore", out rowCount, out pageCount, pageIndex, pageSize))
{
if (dt.Rows.Count > )
{
ltSco = new List<Model.MyScore>();
foreach (System.Data.DataRow item in dt.Rows)
{
Web.Model.MyScore score = new Model.MyScore();
score.Id = int.Parse(item[].ToString());
score.Math = item.IsNull() ? null : (int?)int.Parse(item[].ToString());
score.English = item.IsNull() ? null : (int?)int.Parse(item[].ToString());
ltSco.Add(score);
}
}
return ltSco;
}
} public Web.Model.MyScore GetScore(int id)
{
Web.Model.MyScore score = null;
string sql = "select * from MyScore where id=@id";
System.Data.SqlClient.SqlParameter[] param =
{
new System.Data.SqlClient.SqlParameter("@id",id),
}; using (System.Data.DataTable dt = SqlHelper.ExecuteDataTable(sql, param))
{
if (dt.Rows.Count > )
{
score = new Web.Model.MyScore();
System.Data.DataRow row = dt.Rows[];
score.Id = int.Parse(row[].ToString());
score.Math = row.IsNull() ? null : (int?)int.Parse(row[].ToString());
score.English = row.IsNull() ? null : (int?)int.Parse(row[].ToString());
} return score;
}
}
public Web.Model.MyStudent GetStudent(int id)
{
Web.Model.MyStudent student = null;
string sql = "select * from MyStudent where id=@id";
System.Data.SqlClient.SqlParameter[] param =
{
new System.Data.SqlClient.SqlParameter("@id",id),
};
using (System.Data.SqlClient.SqlDataReader reader = SqlHelper.ExecuteReader(sql, param))
{
if (reader.HasRows)
{
student = new Web.Model.MyStudent();
while (reader.Read())
{
student.Id = reader.GetInt32();
student.sId = this.GetScore(student.Id);
student.Name = reader.IsDBNull() ? null : reader.GetString();
student.Age = reader.IsDBNull() ? null : (int?)reader.GetInt32();
student.Gender = reader.IsDBNull() ? null : (char?)Convert.ToChar(reader[]);
student.CID = reader.IsDBNull() ? null : (int?)int.Parse(reader[].ToString());
student.BirthDay = reader.IsDBNull() ? null : (DateTime?)DateTime.Parse(reader[].ToString());
}
}
return student;
}
} public int ExecuteNonQuery<T>(Web.Model.ActionBehavior behavior, T S)
{
string sql = string.Empty;
System.Data.SqlClient.SqlParameter[] param = null;
if (S is Web.Model.MyStudent)
{
Web.Model.MyStudent stu = S as Web.Model.MyStudent;
switch (behavior)
{
case Web.Model.ActionBehavior.Add:
// int tmp = -1;
//sql = "insert into MyStudent values(@n,@a,@g,@ci,@b)";
sql = "pro_GetIdentityFromMyStu";
//切记: 参数名要和字段名(储存过程)一致和参数要加@
param = new System.Data.SqlClient.SqlParameter[]{
new System.Data.SqlClient.SqlParameter("@name",stu.Name==null?DBNull.Value:(object)stu.Name),
new System.Data.SqlClient.SqlParameter("@age",stu.Age==null?DBNull.Value:(object)stu.Age),
new System.Data.SqlClient.SqlParameter("@gender",stu.Gender==null?DBNull.Value:(object)stu.Gender),
new System.Data.SqlClient.SqlParameter("@classId",stu.CID==null?DBNull.Value:(object)stu.CID),
new System.Data.SqlClient.SqlParameter("@birthday",stu.BirthDay==null?DBNull.Value:(object)stu.BirthDay)
// new System.Data.SqlClient.SqlParameter("@identity",tmp)
};
//但是可以带出参数的准确值
// param[5].Direction = System.Data.ParameterDirection.Output;
// select @identity=@@IDENTITY 这个储存过程没有产生结果集
//System.Data.DataTable a = SqlHelper.ExecuteDataTable(sql, true, param);
//Convert.ToInt32(param[5].Value);
//修改为 select @@IDENTITY 得到程序集
return Convert.ToInt32(SqlHelper.ExecuteDataTable(sql, true, param).Rows[][]);
case Web.Model.ActionBehavior.Modify:
sql = "update MyStudent set Name=@n,Age=@a,Gender=@g,ClassId=@ci,Birthday=@b where id=@id";
param = new System.Data.SqlClient.SqlParameter[]{
new System.Data.SqlClient.SqlParameter("@id",stu.Id),
new System.Data.SqlClient.SqlParameter("@n",stu.Name==null?DBNull.Value:(object)stu.Name),
new System.Data.SqlClient.SqlParameter("@a",stu.Age==null?DBNull.Value:(object)stu.Age),
new System.Data.SqlClient.SqlParameter("@g",stu.Gender==null?DBNull.Value:(object)stu.Gender),
new System.Data.SqlClient.SqlParameter("@ci",stu.CID==null?DBNull.Value:(object)stu.CID),
new System.Data.SqlClient.SqlParameter("@b",stu.BirthDay==null?DBNull.Value:(object)stu.BirthDay)
};
break;
case Web.Model.ActionBehavior.Delete:
sql = "delete from MyStudent where id=@id";//设置的是级联删除
param = new System.Data.SqlClient.SqlParameter[] { new System.Data.SqlClient.SqlParameter("@id", stu.Id) };
break;
}
}
else
{
Web.Model.MyScore score = S as Web.Model.MyScore;
switch (behavior)
{
case Web.Model.ActionBehavior.Modify:
sql = "update MyScore set Math=@m,English=@e where id=@id";
param = new System.Data.SqlClient.SqlParameter[] {
new System.Data.SqlClient.SqlParameter("@id",score.Id),
new System.Data.SqlClient.SqlParameter("@m",score.Math==null?DBNull.Value:(object)score.Math),
new System.Data.SqlClient.SqlParameter("@e",score.English==null?DBNull.Value:(object)score.English)};
break;
case Web.Model.ActionBehavior.Add:
sql = "insert into MyScore values(@id,@m,@e)";
param = new System.Data.SqlClient.SqlParameter[] {
new System.Data.SqlClient.SqlParameter("@id",score.Id),
new System.Data.SqlClient.SqlParameter("@m",score.Math==null?DBNull.Value:(object)score.Math),
new System.Data.SqlClient.SqlParameter("@e",score.English==null?DBNull.Value:(object)score.English)};
break;
/* case Web.Model.ActionBehavior.Delete:
sql = "delete from MyScore where id";*/
}
}
return SqlHelper.ExecuteNonQuery(sql, param);
}
}
SqlHelper.cs
public static class SqlHelper
{
private readonly static string connstr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; #region 这两个方法可以和起来 public static System.Data.SqlClient.SqlDataReader ExecuteReader(string sql, params System.Data.SqlClient.SqlParameter[] param)
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr); using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, con))
{
if (param != null)
{
cmd.Parameters.AddRange(param);
}
con.Open();
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
}
//public static System.Data.SqlClient.SqlDataReader ExecuteGetPaging(out int rowCount, out int pageCount, string proName, int pageIndex, int pageSize = 5)
//{
public static System.Data.SqlClient.SqlDataReader ExecuteGetPaging(string proName, params System.Data.SqlClient.SqlParameter[] param)
{
//System.Data.SqlClient.SqlDataReader reader = null;
//rowCount = pageCount = -1;
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr); using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(proName, con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//System.Data.SqlClient.SqlParameter[] param = {new System.Data.SqlClient.SqlParameter( "@pageIndex",pageIndex),
// new System.Data.SqlClient.SqlParameter("@pageSize",pageSize),
// new System.Data.SqlClient.SqlParameter("@rowCount",rowCount),
// new System.Data.SqlClient.SqlParameter("@pageCount",pageCount) };
//param[2].Direction = System.Data.ParameterDirection.Output;
//param[3].Direction = System.Data.ParameterDirection.Output;
if (param != null)
{
cmd.Parameters.AddRange(param);
}
con.Open();
//reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
//return reader;
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
}
#endregion
#region 和起来的ExecuteReader public static System.Data.SqlClient.SqlDataReader ExecuteReader(string sql, bool isProc, params System.Data.SqlClient.SqlParameter[] param)
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr);
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, con))
{
if (isProc)
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if (param != null)
cmd.Parameters.AddRange(param);
con.Open();
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
}
#endregion public static System.Data.DataTable ExecuteDataTable(string sql, params System.Data.SqlClient.SqlParameter[] param)
{
System.Data.DataTable dt = new System.Data.DataTable();
using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(sql, connstr))
{
if (param != null)
{
adapter.SelectCommand.Parameters.AddRange(param);
}
adapter.Fill(dt);
return dt;
}
} public static System.Data.DataTable ExecuteGetPaging(string proName, out int rowCount, out int pageCount, int pageIndex, int pageSize = )
{
//out特性
rowCount = pageCount = -;
System.Data.DataTable dt = new System.Data.DataTable();
using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(proName, connstr))
{
//查询命令类型
adapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
//参数放在外面是否更合适呢?
System.Data.SqlClient.SqlParameter[] param =
{
new System.Data.SqlClient.SqlParameter("@pageIndex",pageIndex),
new System.Data.SqlClient.SqlParameter("@pageSize",pageSize),
new System.Data.SqlClient.SqlParameter("@rowCount",rowCount),
new System.Data.SqlClient.SqlParameter("@pageCount",pageCount)
};
adapter.SelectCommand.Parameters.AddRange(param);
//参数方向
param[].Direction = System.Data.ParameterDirection.Output;
param[].Direction = System.Data.ParameterDirection.Output;
adapter.Fill(dt);
//为确保转换成功不能使用强制类型转换---参数赋值
// rowCount = param[2].Value;
rowCount = Convert.ToInt32(param[].Value);
pageCount = int.Parse(param[].Value.ToString()); return dt;
}
} public static System.Data.DataTable ExecuteDataTable(string sql, bool isProc, params System.Data.SqlClient.SqlParameter[] param)
{
System.Data.DataTable dt = new System.Data.DataTable();
using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(sql, connstr))
{
if (isProc)//执行的是插入的储存过程,给SelectCommand赋值可以吗? :可以
adapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
if (param != null)
adapter.SelectCommand.Parameters.AddRange(param);
adapter.Fill(dt);
return dt;
}
} public static int ExecuteNonQuery(string sql, params System.Data.SqlClient.SqlParameter[] param)
{
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connstr))
{
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, con))
{
if (param != null)
cmd.Parameters.AddRange(param);
con.Open();
//若级联插入出错不会返回-1,没有报错 会返回状态码 500=服务器内部错误,前台处理一下
int a=cmd.ExecuteNonQuery();
return a;
}
}
}
}
ActionBehavior.cs
public enum ActionBehavior
{
Add,Modify,Delete
}
项目文件:https://pan.baidu.com/s/1i31e65f
AJAX简单的数据增删改与分页应用的更多相关文章
- 【转载】salesforce 零基础开发入门学习(六)简单的数据增删改查页面的构建
salesforce 零基础开发入门学习(六)简单的数据增删改查页面的构建 VisualForce封装了很多的标签用来进行页面设计,本篇主要讲述简单的页面增删改查.使用的内容和设计到前台页面使用的 ...
- salesforce 零基础开发入门学习(六)简单的数据增删改查页面的构建
VisualForce封装了很多的标签用来进行页面设计,本篇主要讲述简单的页面增删改查.使用的内容和设计到前台页面使用的标签相对简单,如果需要深入了解VF相关知识以及标签, 可以通过以下链接查看或下载 ...
- graphql 数据增删改查分页及关联操作(三)
说明: 接第二篇文章,代码也是在第二篇文章之上 本文只是针对mondodb来操作 一.添加相关的包 yarn add Mongoose 二.初始化Mongodb 修改server.ts 导入 impo ...
- node+express+mysql实现简单的数据增删改查
前提 电脑已经安装了node,express,mysql. 实现步骤 1.新建数据库表 附数据表结构: 2.创建exprss项目 express -e myapp 新建一个以ejs为模板的expre ...
- MVC3+EF5.0 code first+Flexigrid+ajax请求+jquery dialog 增删改查
MVC3+EF5.0 code first+Flexigrid+ajax请求+jquery dialog 增删改查 本文的目的: 1.MVC3项目简单配置EF code first生成并初始化数据 ...
- 日历插件FullCalendar应用:(二)数据增删改
接上一篇 日历插件FullCalendar应用:(一)数据展现. 这一篇主要讲使用fullcalendar插件如何做数据的增删改,用到了art.dialog web对话框组件,上一篇用到的webFor ...
- OracleHelper(对增删改查分页查询操作进行了面向对象的封装,对批量增删改操作的事务封装)
公司的一个新项目使用ASP.NET MVC开发,经理让我写个OracleHelper,我从网上找了一个比较全的OracleHelper类,缺点是查询的时候返回DataSet,数据增删改要写很多代码(当 ...
- node-express项目的搭建并通过mongoose操作MongoDB实现增删改查分页排序(四)
最近写了一个用node来操作MongoDB完成增.删.改.查.排序.分页功能的示例,并且已经放在了服务器上地址:http://39.105.32.180:3333. Mongoose是在node.js ...
- C#操作Excel数据增删改查(转)
C#操作Excel数据增删改查. 首先创建ExcelDB.xlsx文件,并添加两张工作表. 工作表1: UserInfo表,字段:UserId.UserName.Age.Address.CreateT ...
随机推荐
- java 形参实参
java方法中传值和传引用的问题是个基本问题,但是也有很多人一时弄不清. (一)基本数据类型:传值,方法不会改变实参的值. public class TestFun { public static v ...
- 【转】Unity LayerMask 的位运算
Unity的Layer Unity是用 int32来表示32个Layer层,int32用二进制来表示一共有32位. 0000 0000 0000 0000 0000 0000 0000 0000 31 ...
- Bluetooth Low Energy介绍
目录 1. 介绍 2. 协议栈 3. 实现方案 3.1 硬件实现方案 3.2 软件实现方案 1. 介绍 Bluetooth low energy,也称BLE(低功耗蓝牙),在4.0规范中提出 BLE分 ...
- C# DateTime类型和时间戳 互相转换
/// <summary> /// 时间戳转为C#格式时间 /// </summary> /// <param name=”timeStamp”></para ...
- MySQL- 锁(2)
InnoDB行锁实现方式 InnoDB行锁是通过给索引上的索引项加锁来实现的,这一点MySQL与Oracle不同,后者是通过在数据块中对相应数据行加锁来实现的.InnoDB这种行锁实现特点意味着:只有 ...
- git push错误解决方案
错误提示: error: The requested URL returned error: 403 Forbidden while accessing https://nanfei9330@gith ...
- Selenium2学习-006-WebUI自动化实战实例-004-解决 Chrome 浏览器证书提示:--ignore-certificate-errors
此文主要讲述 Java 运行 Selenium 脚本时,如何消除 Chrome 浏览器启动后显示的证书错误报警提示,附带 Chrome 参数使浏览器最大化的参数. 希望能对初学 Selenium2 W ...
- win10 + gtx1060 + cuda8.0 + caffe + vs2013
1. 安装cuda8.0 1)先去官网下载cuda8.0 https://developer.nvidia.com/cuda-toolkit 2)下载完之后进行安装,安装时间有点长,请耐心等待,默认 ...
- Ioc-Autofac实现自动的注入
在开发过程中,最郁闷的莫过于当你新增一个Service时,你需要对该Service进行注册,有的是使用代码注入,有的是XML配置注入,不管是哪种类型的注入,经常会出现开发人员忘记注入的情况. 于是我试 ...
- [收藏夹整理]OpenCV部分
OpenCV中文论坛 OpenCV论坛 opencv视频教程目录(初级) OpenCV 教程 Opencv感想和一些分享 tornadomeet 超牛的大神 [数字图像处理]C++读取.旋转和保存bm ...