jQuery ajax提交请求,springmvc控制层接收参数示例以及HTTP请求中Content-Type介绍

通过jQuery发送http请求到springmvc控制层,以及控制层接收参数示例:

    if ($('#instanceTbodyDiv', parent.document).find(':checkbox:checked').length != 1) {
        $.alert({
            icon: 'fa fa-warning',
            content: '请选择1条记录进行操作'
        });
        return false;
    }

    var trs = [];
    $('#pagingTbodyDiv').find(':checkbox:checked').each(function() {
        trs.push($(this).parents('tr'));
    });
    var tr = trs[0];
    var id = tr.find('td:eq(1)').text();
    var name = tr.find('td:eq(4)').text();

    /*单独传参,contentType需要设置成 application/x-www-form-urlencoded
      默认地,表单数据会以这种contentType提交。  */
    $.ajax({
        url: '/workerManage/fixLeader',
        contentType: 'application/x-www-form-urlencoded',
        type: 'post',
        async: false,
        data: {
            id: id,
            name: name
        },
        success: function (result) {
            /*
             @RequestMapping(value="fixLeader", method = {RequestMethod.GET,RequestMethod.POST})
             @ResponseBody
             public JSONResult fixLeader(@RequestParam(value="id", required = true) String id, @RequestParam(value="name", required = true) String name) {
             上面@RequestParam()这些可以不要。
             也可以直接通过url拼接传递参数?id=1&name=haha
             如果controller方法包含参数HttpServletRequest req,那么也可以通过 logger.info(req.getParameter("id") + req.getParameter("name"));获取到传递的值
             */
        }
    });

    /*json传参,注意contentType需要设置成 application/json
    @RequestBody让我们可以直接以application/json请求并在到达controller层获得已反序列化的对象*/
    var vo = {id: id, name: name};
    $.ajax({
        url: '/workerManage/update',
        contentType: "application/json",
        type: "POST",
        data: JSON.stringify(vo),
        timeout: 0,
        success: function (result) {
            /*
             @RequestMapping(value = "/update", method = {RequestMethod.POST})
             @ResponseBody
             public JSONResult update(@RequestBody WorkerEntity workerEntity) {
             */
        }
    });

    /*path传参*/
    $.ajax({
        url: 'workerManage/start/' + id,
        contentType: 'application/json',
        type: "POST",
        success: function (result) {
            /*
             @RequestMapping(value="start/{id}", method=RequestMethod.POST)
             @ResponseBody
             public JSONResult start(@PathVariable("id")int id) {
             */
        }
    });

    /*传递数组*/
    var ids = [];ids.push(1);ids.push(2);
    $.ajax({
        url: 'workerManage/delete',
        contentType: 'application/json',
        type: "POST",
        data: JSON.stringify(ids),
        success: function (result) {
            /*
             @RequestMapping(value = "/delete", produces = "application/json")
             @ResponseBody
             public JSONResult delete(@RequestBody int[] ids) {
             */
        }
    });

    /*url传参*/
    $.ajax({
        url: "/workerManage/get?id=100",
        contentType: "application/json",
        type: "GET",
        timeout: 0,
        success: function (result) {
            /*
             @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
             @ResponseBody
             public WorkerEntity get(int id) {
             */
        }
    });


    /*传一个json对象,然后通过path传其它值*/
    var vo = {notice: "haha"};
    $.ajax({
        url: "/chou/transferPathVal3/zhouzhichao/26",
        contentType: "application/json",
        type: "POST",
        data: JSON.stringify(vo),
        success: function (result) {
            /*
             @RequestMapping(value = "/transferPathVal3/{name}/{age}")
             @ResponseBody
             public JSONResult transferPathVal3(@RequestBody Notice notice, @PathVariable String name, @PathVariable int age) {
             */
        }
    });

    /*传一个json对象,然后通过URL传其它值*/
    var vo = {workerName: "alarmWorker", workerType: 2};
    $.ajax({
        url: "/workerManage/add?name=cc&age=18",
        contentType: "application/json",
        type: "POST",
        data: JSON.stringify(vo),
        timeout: 0,
        success: function (result) {
            /*
             @RequestMapping(value = "/add", method = {RequestMethod.POST})
             @ResponseBody
             public JSONResult add(@RequestBody WorkerEntity workerEntity,String name,int age) {
             */
        }
    });


 


 "application/json; charset=utf-8"  和  "application/x-www-form-urlencoded"的区别:

 "application/json; charset=utf-8"是告诉服务端你是在post json格式的数据,像这样:{ Name : 'John Smith', Age: 23}

"application/x-www-form-urlencoded" 是告诉服务端你是把参数编码放到URL中或者请求体中,像这样:Name=JohnSmith&Age=23

 "application/json; charset=utf-8"  和  "application/x-www-form-urlencoded"都是告诉服务器客户端发送的请求的编码格式。

HTTP 协议是以 ASCII 码传输,建立在 TCP/IP 协议之上的应用层规范。HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。实际上,开发者完全可以自己决定消息主体的格式,只要最后发送的 HTTP 请求满足上面的格式就可以。

但是,数据发送出去,还要服务端解析成功才有意义。

服务端通常是根据请求头(headers)中的 Content-Type 字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。所以说到 POST 提交数据方案,包含了 Content-Type 和消息主体编码方式两部分。

常用的编码方式有:

1.application/x-www-form-urlencoded  最常见的 POST 提交数据的方式。原生 form 表单默认以这种方式提交数据

2.multipart/form-data  一般用来上传文件

3.application/json  用来告诉服务端消息主体是序列化后的 JSON 字符串

4.text/xml   XML作为编码方式

HTTP POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST请求如果不指定请求头RequestHeader,默认使用的Content-Type是text/plain;charset=UTF-8。

jquery在执行post请求时,会默认设置Content-Type为application/x-www-form-urlencoded,所以服务器能够正确解析,而使用原生ajax请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。

curl发送http请求
curl -X POST 'http://localhost:8080/formPost' -d 'id=1&name=foo&mobile=13612345678'
curl -X POST -H "Content-Type: application/json" 'http://localhost:8080/jsonPost' -d '{"id":2,"name":"foo","mobile":"13656635451"}'
curl -X POST -H "Content-Type: application/json" 'http://localhost:8080/mixPost?sex=1' -d '{"id":2,"name":"foo","mobile":"13656635451"}'

参考:http://blog.csdn.net/mhmyqn/article/details/25561535

https://stackoverflow.com/questions/9870523/differences-in-application-json-and-application-x-www-form-urlencoded

http://blog.csdn.net/mhmyqn/article/details/25561535

http://blog.csdn.net/tycoon1988/article/details/40080691

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现将 AJAX 异步提交的表单数据传递给 Spring MVC,可以采用以下步骤: 1. 在前端页面,使用 jQueryAJAX 方法将表单数据异步提交到后端的 Spring MVC 控制。 2. 在 Spring MVC 控制,使用 @RequestParam 注解或 HttpServletRequest 对象来获取 AJAX 提交的表单数据。 3. 对表单数据进行处理和验证,并将处理后的结果返回给前端页面或者进行其他业务逻辑操作。 以下是一个简单的示例代码: 前端页面: ```html <form id="myForm"> <input type="text" name="username"> <input type="password" name="password"> <button type="button" onclick="submitForm()">Submit</button> </form> <script> function submitForm() { var formData = $('#myForm').serialize(); $.ajax({ url: '/submitForm', type: 'POST', data: formData, success: function(result) { // 处理返回结果 } }); } </script> ``` Spring MVC 控制器: ```java @Controller public class MyController { @PostMapping("/submitForm") @ResponseBody public String submitForm(@RequestParam("username") String username, @RequestParam("password") String password) { // 处理表单数据 return "success"; } } ``` 在上述示例,前端页面的 submitForm() 方法使用 jQuery 的 serialize() 方法将表单数据序列化为字符串,并使用 AJAX 异步提交到后端的 Spring MVC 控制。 Spring MVC 控制的 submitForm() 方法使用 @RequestParam 注解获取 AJAX 提交的表单数据,并对表单数据进行处理和验证,最后返回一个字符串表示处理结果。其,@ResponseBody 注解表示返回的字符串将直接作为响应体返回给前端页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值