首页 > 技术文章 > Ajax表单提交方式

xiaofuzi123456 2020-07-12 15:31 原文

和提交普通表单一样发送数据

浏览器端代码

$("#ajaxform").click(function () {
                //在我们像提交表单一样发送数据时,不用把JSON对象转换为JSON字符串
                var requestBody = {
                    "empId":999,
                    "empName":"harry",
                    "empSalary":128.56
                };

                $.ajax({
                    "url":"ajax/send/form/data.action",	// 请求的目标地址
                    "type":"post",					// 请求方式
                    "data":requestBody,				// 请求体数据
                    "contentType":"application/x-www-form-urlencoded",	//默认值,可以省略该项
                    "dataType":"json",			// 服务器端返回数据的解析方式
                    "success":function(response) {			// 服务器处理请求成功,执行这个函数,响应体从参数这里传入

                        // response已经解析为JSON对象,可以直接使用“.属性名”方式访问具体属性
                        var result = response.result;

                        // 如果返回结果成功,显示成功(逻辑成功)
                        if("SUCCESS" == result) {
                            alert("SUCCESS");
                        }

                        // 如果返回结果失败,显示消息(逻辑失败)
                        if("FAILED" == result) {

                            var message = response.message;

                            alert(message);
                        }

                    },

                    "error":function(response){			// 处理请求失败,例如:404、500、400等等

                        alert(response);

                    }
                });
            }); 

使用开发者工具查看请求体

controller代码

 @ResponseBody
    @RequestMapping("/ajax/send/form/data")
    public ResultEntity<String> receiveFormData(Employee employee) {

        System.out.println(employee);

        return ResultEntity.successWithoutData();
    }

整个请求体是一个JSON数据

浏览器端代码

$("#ajaxjson").click(function(){

               // Ajax请求的请求体如果是JSON格式,那么需要先将数据封装为JSON对象
               var jsonObj = [
                   {
                       "empId":666,
                       "empName":"jerry",
                       "empSalary":123.321
                   },
                   {
                       "empId":555,
                       "empName":"bob",
                       "empSalary":456.654
                   },
                   {
                       "empId":444,
                       "empName":"kate",
                       "empSalary":666.666
                   }
               ];

               // 将JSON对象转换为JSON字符串
               var requestBody = JSON.stringify(jsonObj);

               // 发送Ajax请求
               $.ajax({
                   "url":"ajax/send/json/data.action",	// 请求的目标地址
                   "type":"post",					// 请求方式
                   "data":requestBody,				// 请求体数据
                   "contentType":"application/json;charset=UTF-8",	//非默认值,不能省略
                   "dataType":"json",				// 服务器端返回数据的解析方式
                   "success":function(response) {			// 服务器处理请求成功,执行这个函数,响应体从参数这里传入

                       // response已经解析为JSON对象,可以直接使用“.属性名”方式访问具体属性
                       var result = response.result;

                       // 如果返回结果成功,显示成功(逻辑成功)
                       if("SUCCESS" == result) {
                           alert("SUCCESS");
                       }

                       // 如果返回结果失败,显示消息(逻辑失败)
                       if("FAILED" == result) {

                           var message = response.message;

                           alert(message);
                       }

                   },

                   "error":function(response){			// 处理请求失败,例如:404、500、400等等

                       alert(response);

                   }
               });

           });

使用开发者工具查看请求体

Controller代码

@ResponseBody
   @RequestMapping("/ajax/send/json/data")
   public ResultEntity<String> receiveJsonData(@RequestBody List<Employee> empList) {

       for (Employee employee : empList) {
           System.out.println(employee);
       }

       return ResultEntity.successWithoutData();
   }

小结

使用JSON格式作为请求体去传送数据,非常适合发送结构复杂的大对象数据。JSON格式和Java类型直接对应,不需要额外封装专门接收请求参数的实体类。

使用时需要注意的点:

  • JSON对象需要使用JSON.stringify()转换为JSON字符串
  • contentType要设置成application/json;charset=UTF-8
  • Controller方法接收使用Java类型形参前需要使用@RequestBody注解

推荐阅读