How to use ajax for front-end and back-end interaction

Method of using ajax for front-end and back-end interaction: (I only tested the method of using json object as a parameter, and I did not test other methods.) 1.
Front-end method:
Parameter passing method: POST
request type: json object
response type: json object

 function test() {
    
    
            var param1Value = "Hello";
            var param2Value = "World";

            // 构建发送给服务器的JSON对象
            var jsonobj = {
    
    
                param1: param1Value,
                param2: param2Value
            };
            $.ajax({
    
    
                type: "POST",//传参方式
                url: "test01.aspx/tt",  // 这里根据你的WebMethod路径进行修改
                data: JSON.stringify(jsonobj), //请求类型,将对象序列化为JSON字符串后传递到后端
                contentType: "application/json; charset=utf-8",
                dataType: "json", //响应类型
                success: function (data) {
    
    
                    // 请求成功的回调函数
                    // data是服务器返回的JSON对象
                    console.log(data);
                },
                error: function (error) {
    
    
                    // 请求失败的回调函数
                    console.error(error);
                }
            });
        }

2. Backend method: There is no need to create a class to receive the json string from the front end. It should be noted that the receiving parameters used must be consistent with the key names in the json object defined by the front end.

 [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string tt(string param1, string param2)
        {
    
    
            //后端创建json对象
            var resultObject = new
            {
    
    
                Message = "Success",
                Data = new
                {
    
    
                    Param1Result = param1.ToUpper(),
                    Param2Result = param2.ToLower(),
                    SomeOtherData = "Hello from server!"
                }
            };

            // 将对象序列化为JSON字符串并返回
            return Newtonsoft.Json.JsonConvert.SerializeObject(resultObject);
        }

Guess you like

Origin blog.csdn.net/hmwz0001/article/details/131938450