jquery实现页面无刷新上升下降排序
打开sqlserver 建一个数据库 代码如下:
create database Test
on primary
(
/*--数据文件的具体描述--*/
name='Test', -- 主数据文件的逻辑名称
filename='E:\Test.mdf',
size=3mb, --主数据文件的初始大小
maxsize=10mb, -- 主数据文件增长的最大值
filegrowth=15%--主数据文件的增长率
)
log on
(
/*--日志文件的具体描述,各参数含义同上--*/
name='Test_log',
filename='E:\Test.ldf',
size=2mb,
filegrowth=1mb
)
use Test
go
if object_id(N'orderBy',N'U') is not null drop table orderBy
create table orderBy(
ID int identity(1,1) primary key,--主键自增
Name nvarchar(max),
orderId int)
go
新建一个文件夹取名为“UpDown”,打开 VS 2012 >文件>新建>网站>ASP.NET 空网站,项目Web位置浏览到“UpDown”目录,
在项目根目录创建文件夹App_Code文件夹,将微软的SQLHelper.cs类 文件拷贝到App_Code文件夹,SQLHelper.cs 可以在微软官方下载。
新建js文件夹,将jquery-1.7.2.min.js文件拷贝到js文件夹。jquery-1.7.2.min.js 可以在jquery官网下载。
打开web.config 在<configuration></configuration>中间添加
<appSettings>
<add key="Test" value="Server=.;User id =sa;Pwd=sa;Database=Test"/>
</appSettings>
在项目根目录添加一个Web服务取名为“WS.asmx”,勾上将代码放在单独的文件中,
WS.cs 文件代码如下:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class WS : System.Web.Services.WebService {
public static string connStr = System.Configuration.ConfigurationManager.AppSettings["Test"].ToString();
/// <summary>
/// 下拉框查询方法
/// </summary>
/// <returns></returns>
[WebMethod]
public string SelectName() {
string sqlStr = "select * from orderBy order by orderId";
DataSet ds = SqlHelper.ExecuteDataset(connStr, CommandType.Text, sqlStr);
string listStr = "";
if (ds.Tables[0].Rows.Count == 0)
{
return "";
}
foreach (DataRow dr in ds.Tables[0].Rows)
{
listStr += "<option value='" + dr["ID"].ToString() + "'>" + dr["Name"].ToString() + "</option>";
}
return listStr;
}
/// <summary>
/// 表格查询方法
/// </summary>
/// <returns></returns>
[WebMethod]
public string selectNameTable() {
string sqlStr = "select * from orderBy order by orderId";
DataSet ds = SqlHelper.ExecuteDataset(connStr, CommandType.Text, sqlStr);
if (ds.Tables[0].Rows.Count == 0)
{
return "";
}
string strHtml = "<table>";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
strHtml += "<tr id='_tr" + ds.Tables[0].Rows[i]["orderId"] + "'><td>" + ds.Tables[0].Rows[i]["Name"].ToString() + "</td><td><input type='button' value='上升' onclick='Up(" + ds.Tables[0].Rows[i]["orderId"] + ")' /></td><td><input type='button' value='下降' onclick='Down(" + ds.Tables[0].Rows[i]["orderId"] + ")' /></td></tr>";
}
return strHtml + "</table>";
}
/// <summary>
/// 添加方法
/// </summary>
/// <param name="Name">参数Name为前台JS传入</param>
/// <returns></returns>
[WebMethod]
public int InsertName(string Name) {
//查询orderBy表内数据
DataSet ds = SqlHelper.ExecuteDataset(connStr, CommandType.Text, "select * from orderBy where Name='" + Name + "'");
//判断如果存在就返回0
if (ds.Tables[0].Rows.Count>0)
{
return 0;
}
string sqlStr = "insert into orderBy (Name) values('"+Name+"');update orderBy set orderId=SCOPE_IDENTITY() where ID=SCOPE_IDENTITY()";
int i=SqlHelper.ExecuteNonQuery(connStr, CommandType.Text, sqlStr);
return i;
}
/// <summary>
/// 修改方法
/// </summary>
/// <param name="Name">参数Name,ID前台JS传入</param>
/// <param name="ID"></param>
/// <returns></returns>
[WebMethod]
public int UpdateName(string Name,int ID) {
DataSet ds = SqlHelper.ExecuteDataset(connStr,CommandType.Text,"select * from orderBy where Name='"+Name+"'");
if (ds.Tables[0].Rows.Count > 0)
{
return 0;
}
string sqlStr = "update orderBy set Name='"+Name+"' where ID="+ID;
int i = SqlHelper.ExecuteNonQuery(connStr, CommandType.Text, sqlStr);
return i;
}
/// <summary>
/// 删除方法
/// </summary>
/// <param name="Name"></param>
/// <param name="ID"></param>
/// <returns></returns>
[WebMethod]
public int DeleteName(string Name,int ID) {
string sqlStr = "delete from orderBy where Name='"+Name+"' and ID="+ID;
int i = SqlHelper.ExecuteNonQuery(connStr,CommandType.Text,sqlStr);
return i;
}
/// <summary>
/// 修改排序方法
/// </summary>
/// <param name="orderA"></param>
/// <param name="orderB"></param>
/// <returns></returns>
[WebMethod]
public int UpdateNameOrder(int orderA,int orderB) {
DataSet ds = SqlHelper.ExecuteDataset(connStr, CommandType.Text, "select ID from orderBy where orderId=" + orderA + ";select ID from orderBy where orderId=" + orderB + "");
int IDA =Convert.ToInt32(ds.Tables[0].Rows[0][0]);
int IDB =Convert.ToInt32(ds.Tables[1].Rows[0][0]);
string sqlstr = "update orderBy set orderId=" + orderB + " where ID="+IDA+";update orderBy set orderId="+orderA+" where ID="+IDB+"";
int i = SqlHelper.ExecuteNonQuery(connStr,CommandType.Text,sqlstr);
return i;
}
}
新建一个Default.aspx页面 代码如下:
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
//页面加载完成执行
$(document).ready(function () {
//绑定添加按钮的click方法Insert
$("#BtnInsert").bind('click', { foo: 'click' }, Insert);
//绑定修改按钮的click方法Update 并设为 不可操作
$("#BtnUpdate").bind('click', { foo: 'click' }, Update).attr('disabled', 'disabled');
//绑定删除按钮的click方法Delete 并设为 不可操作
$("#BtnDelete").bind('click', { foo: 'click' }, Delete).attr('disabled', 'disabled');
//执行selectName 方法
selectName();
//执行selectNameTable方法
selectNameTable();
//绑定下拉框的change事件
$("#Select1").change(function () {
if ($("#Select1").val() != 0) {
$("#BtnInsert").attr('disabled', 'disabled');
$("#BtnUpdate").removeAttr('disabled');
$("#BtnDelete").removeAttr('disabled');
$("#txtName").val($("#Select1").find("option:selected").text());
} else {
$("#txtName").val("");
$("#BtnInsert").removeAttr('disabled');
$("#BtnUpdate").attr('disabled', 'disabled');
$("#BtnDelete").attr('disabled', 'disabled');
}
})
})
//添加方法
function Insert(events) {
if ($("#txtName").val() == "") {
alert("不能为空!");
return;
}
if ($("#Select1").val() == 0) {
var options = {
type: "POST",
url: "WS.asmx/InsertName",
data: "{Name:'" + $("#txtName").val().trim()
+ "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d > 0) {
selectName();
selectNameTable();
$("#BtnUpdate").attr('disabled', 'disabled');
$("#BtnDelete").attr('disabled', 'disabled');
alert("添加成功!")
} else {
alert("已存在!")
}
}
};
$.ajax(options);
}
}
//修改方法
function Update(events) {
if ($("#Select1").val() != 0) {
//判断如果下拉框的文本内容和文本框的内容一样 弹出提示“未修改!”
if ($("#txtName").val() == $("#Select1").find("option:selected").text()) {
alert("未修改!");
return;
}
var options = {
type: "POST",
url: "WS.asmx/UpdateName",
data: "{Name:'" + $("#txtName").val().trim()
+ "',ID:" + $("#Select1").val() + "}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d > 0) {
selectName();
selectNameTable();
$("#BtnUpdate").attr('disabled', 'disabled');
$("#BtnDelete").attr('disabled', 'disabled');
$("#BtnInsert").removeAttr('disabled');
alert("修改成功!")
} else {
alert("修改失败!已有相同的名称")
}
}
};
$.ajax(options);
}
}
//删除方法
function Delete(events) {
if ($("#Select1").val() != 0) {
var options = {
type: "POST",
url: "WS.asmx/DeleteName",
data: "{Name:'" + $("#Select1").find("option:selected").text()
+ "',ID:" + $("#Select1").val() + "}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d > 0) {
$("#txtName").val("");
selectName();
selectNameTable();
$("#BtnInsert").removeAttr('disabled');
$("#BtnUpdate").attr('disabled', 'disabled');
$("#BtnDelete").attr('disabled', 'disabled');
alert("删除成功!")
} else {
alert("删除失败!")
}
}
};
$.ajax(options);
}
}
//下拉框查询方法
function selectName() {
$("#Select1").empty();
var options = {
type: "POST",
url: "WS.asmx/SelectName",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
$("#Select1").append("<option value='0'>添加姓名</option>" + response.d);
}
};
$.ajax(options);
}
//表格查询方法
function selectNameTable() {
$("#Show_Table").empty();
var options = {
type: "POST",
url: "WS.asmx/SelectNameTable",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != "") {
$("#Show_Table").html(response.d);
}
}
};
$.ajax(options);
}
//上升方法
function Up(o) {
o = $("#_tr" + o);
if (o.prev().length > 0) {
//克隆o
var tmp = o.clone();
//匹配o的前一个元素
var oo = o.prev();
//将tem中的_tr替换为空得到orderId
var orderA = tmp.attr("id").replace("_tr", "");
//将oo中的_tr替换为空得到orderId
var orderB = oo.attr("id").replace("_tr", "");
var options = {
type: "POST",
url: "WS.asmx/UpdateNameOrder",
data: "{orderA:" + orderA + ",orderB:" + orderB + "}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d > 0) {
selectName();
selectNameTable();
$("#BtnInsert").removeAttr('disabled');
$("#BtnUpdate").attr('disabled', 'disabled');
$("#BtnDelete").attr('disabled', 'disabled');
alert("修改排序成功!");
} else {
alert("修改排序失败!");
}
}
};
$.ajax(options);
}
}
//下降方法
function Down(o) {
o = $("#_tr" + o);
if (o.next().length > 0) {
//克隆o
var tmp = o.clone();
//匹配o的后一个元素
var oo = o.next();
//将tem中的_tr替换为空得到orderId
var orderA = tmp.attr("id").replace("_tr", "");
//将oo中的_tr替换为空得到orderId
var orderB = oo.attr("id").replace("_tr", "");
var options = {
type: "POST",
url: "WS.asmx/UpdateNameOrder",
data: "{orderA:" + orderA + ",orderB:" + orderB + "}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d > 0) {
selectName();
selectNameTable();
$("#BtnInsert").removeAttr('disabled');
$("#BtnUpdate").attr('disabled', 'disabled');
$("#BtnDelete").attr('disabled', 'disabled');
alert("修改排序成功!");
} else {
alert("修改排序失败!");
}
}
};
$.ajax(options);
}
}
</script>
</head>
<body>
<div>
<input id="txtName" type="text" />名字
<select id="Select1" style="width: 100px">
<option></option>
</select>
<input id="BtnInsert" type="button" value="添加" />
<input id="BtnUpdate" type="button" value="修改" />
<input id="BtnDelete" type="button" value="删除" />
</div>
<div id="Show_Table">
</div>
</body>
</html>
好了,整个示例到此就已经全部写完了,欢迎大家能踊跃指出代码中的不足,提出宝贵的意见。谢谢!