帮我写一个 用ajax实现增删改查前后端,,使用html文件、js文件中应用ajax为前端,一般处理程序ashx为后端,使用SqlServer数据库
时间: 2024-04-30 18:17:22 浏览: 181
好的,我明白了,下面是对您的问题的回答:
首先,要实现增删改查功能,需要在SqlServer数据库中创建对应的表,并在后台ashx文件中编写对应的增删改查方法。以下是示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// Handler 的摘要说明
/// </summary>
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = context.Request.QueryString["action"];
string result = "";
switch (action)
{
case "add": // 添加数据
result = AddData(context.Request.Form["name"], context.Request.Form["age"], context.Request.Form["sex"]);
break;
case "delete": // 删除数据
result = DeleteData(context.Request.QueryString["id"]);
break;
case "update": // 更新数据
result = UpdateData(context.Request.Form["id"], context.Request.Form["name"], context.Request.Form["age"], context.Request.Form["sex"]);
break;
case "query": // 查询数据
result = QueryData();
break;
default:
break;
}
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
// 添加数据
private string AddData(string name, string age, string sex)
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "INSERT INTO UserInfo (Name, Age, Sex) VALUES (@Name, @Age, @Sex)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Age", age);
cmd.Parameters.AddWithValue("@Sex", sex);
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
return "添加成功!";
}
else
{
return "添加失败!";
}
}
}
}
// 删除数据
private string DeleteData(string id)
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "DELETE FROM UserInfo WHERE Id = @Id";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Id", id);
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
return "删除成功!";
}
else
{
return "删除失败!";
}
}
}
}
// 更新数据
private string UpdateData(string id, string name, string age, string sex)
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "UPDATE UserInfo SET Name = @Name, Age = @Age, Sex = @Sex WHERE Id = @Id";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Age", age);
cmd.Parameters.AddWithValue("@Sex", sex);
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
return "修改成功!";
}
else
{
return "修改失败!";
}
}
}
}
// 查询数据
private string QueryData()
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string sql = "SELECT * FROM UserInfo";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
DataTable dataTable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataTable);
string jsonStr = DataTableToJson(dataTable);
return jsonStr;
}
}
}
// DataTable转换为JSON字符串
private string DataTableToJson(DataTable table)
{
System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow dataRow in table.Rows)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataColumn column in table.Columns)
{
dict[column.ColumnName] = dataRow[column];
}
list.Add(dict);
}
return jss.Serialize(list);
}
}
}
```
接下来,需要在html中编写前端页面,使用jquery库来调用服务端的ashx方法,实现增删改查功能。以下是示例代码:
```html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="Scripts/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function () {
loadData();
$("#btnAdd").click(function () {
var name = $("#txtName").val();
var age = $("#txtAge").val();
var sex = $("#selSex").val();
$.ajax({
type: "POST",
url: "Handler.ashx?action=add",
data: { "name": name, "age": age, "sex": sex },
dataType: "text",
success: function (data) {
alert(data);
loadData();
},
error: function (err) {
alert(err);
}
});
});
$("#btnUpdate").click(function () {
var id = $("#txtId").val();
var name = $("#txtName").val();
var age = $("#txtAge").val();
var sex = $("#selSex").val();
$.ajax({
type: "POST",
url: "Handler.ashx?action=update",
data: { "id": id, "name": name, "age": age, "sex": sex },
dataType: "text",
success: function (data) {
alert(data);
loadData();
},
error: function (err) {
alert(err);
}
});
});
$("#tbody").on("click", ".btnDelete", function () {
var id = $(this).attr("data-id");
if (confirm("确定要删除该记录吗?")) {
$.ajax({
type: "GET",
url: "Handler.ashx?action=delete",
data: { "id": id },
dataType: "text",
success: function (data) {
alert(data);
loadData();
},
error: function (err) {
alert(err);
}
});
}
});
});
function loadData() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=query",
dataType: "json",
success: function (data) {
var tbody = $("#tbody");
tbody.empty();
$.each(data, function (index, item) {
var tr = $("<tr>");
var tdId = $("<td>").html(item.Id);
var tdName = $("<td>").html(item.Name);
var tdAge = $("<td>").html(item.Age);
var tdSex = $("<td>").html(item.Sex);
var tdOperate = $("<td>").html("<a href='#' class='btnDelete' data-id='" + item.Id + "'>删除</a>");
tr.append(tdId).append(tdName).append(tdAge).append(tdSex).append(tdOperate);
tbody.append(tr);
});
},
error: function (err) {
alert(err);
}
});
}
</script>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<div style="margin-top: 20px;">
<input type="hidden" id="txtId" />
<input type="text" id="txtName" placeholder="姓名" />
<input type="text" id="txtAge" placeholder="年龄" />
<select id="selSex">
<option value="男">男</option>
<option value="女">女</option>
</select>
<button id="btnAdd">添加</button>
<button id="btnUpdate">修改</button>
</div>
</body>
</html>
```
这样,一个使用ajax实现增删改查的前后端页面就完成了。如果需要修改数据库连接字符串,只需要在Web.config中修改即可。
阅读全文