使用Ajax实现简单的增删查改&&前端Ajax传的值,后端如何获取

本人小白一个。
文章中所说可能有些不足,因为这些是我自己在写项目的过程中所使用的Ajax。
如有不对的地方,欢迎评论提出建议。

一、Ajax最基本语法

话不多说,直接上代码

$.ajax({
            url: "/User/GetUser",(这里写请求路径)
            type: "get",(这里写请求方式(post/get))
            dataType: "json",(这里写数据格式,我这里写的是json类型)
            contentType: "application/json;charset=utf-8",(这里写数据格式,我这里写的是json类型)
            success: function (data) {
            	(這是請求成功,執行的方法)
            },
            error:function(){
            	(这是请求失败,执行的方法)
            }
        })

contentType: 告诉服务器,我要发什么类型的数据
dataType:告诉服务器,我要想什么类型的数据

以上就是最基本的语法

二、增删查改

对于增删查改,我们要用到不同的请求方式
(不过都使用一种请求方式,也是可以的)

Get请求和Post请求的区别
1.使用Get请求时,参数在URL中显示,而使用Post方式,则不会显示出来

2.使用Get请求发送数据量小,Post请求发送数据量大

1.查询(Get请求)

查询其实很简单,就直接使用最基础的语法就可
如果要传参数过去,就在url后面加上?就可,多个参数用&/&&连接即可

$.ajax({
            url: "User/GetUser",
//如果要传参数过去,就在url后面加上?就可,多个参数用&/&&连接即可
 //传一个ID过去url:"User/GetUser?ID="+2,
  //传两个参数:url:"User/GetUser?ID="+2+"&Name=CSDN",
            type: "get",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: function (data) {
            	(這是請求成功,執行的方法)
            },
            error:function(){
            	(这是请求失败,执行的方法)
            }
        })

2.增删改(Post请求)

//声明一个对象,这个对象就用来放你增删改需要传的数据
			var fd = {
				//属性名:值
                Name: $("#Name").val(),
                Sex: $("#Sex").val()
            }
            //再把声明的对象转换成json格式,传到后台(JSON.stringify(对象))
            $.ajax({
                url: "User/ExcUser?DataSoru=" + JSON.stringify(fd),
                type: "post",
                datatype: "json",
                contentype: "application/json;charset=utf-8",
                success: function (data) {
                    if (data = 1) {
                         alert('成功!')
                    }
                    if (data = 0) {
                        alert('失敗!')
                    }
                },
                error: function () {
                    alert('失敗!')
                }
            })

三、后台(MVC/WebForm)

1.MVC(Post请求)

查詢

public IActionResult GetPerson(string Name) {
            var PersonData = 數據源.Where(y => y.ID == workID);
            return new JsonResult(PersonData);
        }

增刪改,我这里是使用EF+MVC

//我这里的Friend是一个类,与前端传入的Formdata对象是一致的
//所以可以直接拿到传来的值
public ActionResult AddColl(Friend friend) {
	//删除和新增
	if (db.Friends.Where(f=>f.friedID==friend.friedID && f.userID== friend.userID).ToList().Count>0)
            {
 //-------------------删除,模型.Remove------------------------------
                int id = db.Friends.Where(c => c.friedID == friend.friedID && c.userID == friend.userID).ToList()[0].Id;
                //通过find方法,查找符合传入ID的数据,进行删除
                Friend friend1 = db.Friends.Find(id);
                db.Friends.Remove(friend1);
                if (db.SaveChanges()>0)
                {
                    return Content("3");
                }
                else
                {
                    return Content("4");
                }
            }
            else
            {
 //-------------------新增,模型.Remove----------------------------------
                //通过find方法,查找符合传入ID的数据,进行删除
                db.Friends.Add(friend);
                if (db.SaveChanges()>0)
                {
                    return Content("1");
                }
                else
                {
                    return Content("2");
                }
            }
}

2.WebForm(Post请求)

一般处理器(ashx),处理多种方法

Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        context.Response.ContentType = "text/plain"
        Dim action As String = context.Request.QueryString("action").ToString()
        Select Case action
            Case "GetParByID"
                GetParByID(context, context.Request.QueryString("ID"))
            Case "XiuGai"
                XiuGai(context, context.Request.QueryString("DataSoru"))
            Case "Add"
                Add(context, context.Request.QueryString("DataSoru"))
        End Select

    End Sub

'查詢
 Public Sub GetParByID(context As HttpContext, ID As Integer)
        
        context.Response.Write(JsonConvert.SerializeObject(PraData))
    End Sub
 '增刪改
Public Sub XiuGai(context As HttpContext, Pra As String)
        If Pra IsNot Nothing Then
            Dim pa As ParametersInfo = New ParametersInfo
            pa = JsonConvert.DeserializeObject(Of ParametersInfo)(Pra)
            If ParametersDAL.Parameters_update(pa.ParametersPKID, pa.PContents) > 0 Then
                context.Response.Write(1)
            Else
                context.Response.Write(0)
            End If

        End If
    End Sub

四、前端Ajax传的值,后端如何获取

1.获取单纯的值

//直接通过,Request["属性名"],获取这个名字
//比如:
我的ajax地址:url: "User/Login?UserNo=12272&&UserPassWord=123",
那么后台直接:
1、Request["属性名"]直接获取值
	public ActionResult Login()
    {
          string UserNo= Request["UserNo"];   
          //此时Request["UserNo"]=12272
          string UserPassWord= Request["UserPassWord"];  
          //此时Request["UserPassWord"]=123
    }
       		
2、 方法中的参数名称与前端传入的参数名称一致即可
	public ActionResult Login(string UserNo,string UserPassWord)
	{
		//此时UserNo = 12272
		//此时UserPassWord = 123
	}
 

2.获取对象

前端

//声明一个对象,这个对象就用来放你增删改需要传的数据
			var fd = {
				//属性名:值
                UserNo: $("#NoText").val(),
                UserPassWord: $("#PassWordText").val()
            }
            //再把声明的对象转换成json格式,传到后台(JSON.stringify(对象))
            $.ajax({
                url: "User/Login?DataSoru=" + JSON.stringify(fd),
                type: "post",
                datatype: "json",
                contentype: "application/json;charset=utf-8",
                success: function (data) {}
            })

后端

两种方法
1、Request["属性名"]直接获取值
	public ActionResult Login()
    {
          string UserNo= Request["UserNo"];   
          //此时Request["UserNo"]=12272
          string UserPassWord= Request["UserPassWord"];  
          //此时Request["UserPassWord"]=123
    }
       		
2、 创建一个类,类中的参数名称与前端传入的参数名称一致即可
	//一般这种类都是你业务中的类,不需要在这里再创一个,直接调用你业务中的类即可
	public class User
    {
    	public string UserNo {get;set;}
    	public string UserPassWord {get;set;}
    }
	public ActionResult Login(User users)
	{
		//此时users中的对象值,就是你传入的值
		string UserNo= users.UserNo;   
        //此时UserNo=12272
        string UserPassWord= users.UserPassWord;  
        //此时UserPassWord=123
	}
 
  • 3
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单增删查改展示的示例,使用PHP后端和JavaScript前端。 1. 设置数据库连接 ```php <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } ?> ``` 2. 创建表格和表单 ```html <!DOCTYPE html> <html> <head> <title>增删查改展示</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="script.js"></script> </head> <body> <h1>增删查改展示</h1> <table id="table"> <thead> <tr> <th>ID</th> <th>名称</th> <th>价格</th> <th>数量</th> <th>操作</th> </tr> </thead> <tbody> <!-- 从数据库中获取数据并展示 --> </tbody> </table> <h2>添加/编辑商品</h2> <form id="form"> <label for="name">名称:</label> <input type="text" name="name" id="name"><br> <label for="price">价格:</label> <input type="number" name="price" id="price"><br> <label for="quantity">数量:</label> <input type="number" name="quantity" id="quantity"><br> <input type="hidden" name="id" id="id"> <input type="submit" value="提交"> </form> </body> </html> ``` 3. 获取数据并展示 ```javascript $(document).ready(function() { // 从数据库中获取数据 $.ajax({ url: "get_data.php", type: "GET", success: function(data) { // 解析数据并展示在表格中 $("#table tbody").html(data); } }); }); ``` 4. 处理添加和编辑请求 ```javascript $(document).ready(function() { $("#form").submit(function(event) { event.preventDefault(); var form_data = $(this).serialize(); $.ajax({ url: "save_data.php", type: "POST", data: form_data, success: function(data) { // 重新获取数据并展示 $.ajax({ url: "get_data.php", type: "GET", success: function(data) { $("#table tbody").html(data); } }); // 清空表单 $("#form")[0].reset(); $("#id").val(""); } }); }); }); ``` 5. 处理删除请求 ```javascript $(document).ready(function() { $(document).on("click", ".delete", function() { var id = $(this).data("id"); $.ajax({ url: "delete_data.php", type: "POST", data: {id: id}, success: function(data) { // 重新获取数据并展示 $.ajax({ url: "get_data.php", type: "GET", success: function(data) { $("#table tbody").html(data); } }); } }); }); }); ``` 6. 处理编辑请求 ```javascript $(document).ready(function() { $(document).on("click", ".edit", function() { var id = $(this).data("id"); $.ajax({ url: "get_data_by_id.php", type: "POST", data: {id: id}, dataType: "json", success: function(data) { $("#name").val(data.name); $("#price").val(data.price); $("#quantity").val(data.quantity); $("#id").val(data.id); } }); }); }); ``` 7. 编写PHP后端代码 get_data.php - 获取所有数据并展示在表格中 ```php <?php include "connect.php"; $sql = "SELECT * FROM products"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" . $row["price"] . "</td><td>" . $row["quantity"] . "</td><td><button class='edit' data-id='" . $row["id"] . "'>编辑</button> <button class='delete' data-id='" . $row["id"] . "'>删除</button></td></tr>"; } } else { echo "0 结果"; } $conn->close(); ?> ``` save_data.php - 处理添加和编辑请求 ```php <?php include "connect.php"; $name = $_POST["name"]; $price = $_POST["price"]; $quantity = $_POST["quantity"]; $id = $_POST["id"]; if ($id) { $sql = "UPDATE products SET name='$name', price='$price', quantity='$quantity' WHERE id='$id'"; } else { $sql = "INSERT INTO products (name, price, quantity) VALUES ('$name', '$price', '$quantity')"; } if ($conn->query($sql) === TRUE) { echo "成功"; } else { echo "错误: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> ``` delete_data.php - 处理删除请求 ```php <?php include "connect.php"; $id = $_POST["id"]; $sql = "DELETE FROM products WHERE id='$id'"; if ($conn->query($sql) === TRUE) { echo "成功"; } else { echo "错误: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> ``` get_data_by_id.php - 根据ID获取数据并返回JSON格式 ```php <?php include "connect.php"; $id = $_POST["id"]; $sql = "SELECT * FROM products WHERE id='$id'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); echo json_encode($row); } else { echo "0 结果"; } $conn->close(); ?> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值