欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

3个用例说明 ajax请求+springmvc 的主要的2种 contentType (除开multipart/form-data )

程序员文章站 2022-07-15 15:37:43
...

springmvc 后端接收ajax请求, 常见的有3种contentType 类型, 这里主要讲两种contentType 请求类型
1:contentType = “application/json;charset=UTF-8”
2:contentType = “application/x-www-form-urlencoded;charset=UTF-8” (默认)

另外还可通过 dataType 约定了服务器数据访问类型
dataType 默认= “json” 可写可不写 .

用例1

  • 前端
function search1() {
        var carid = $("input[name='carid']").val();        
        var data1 = {
            "pageindex" : "1",
            "pagesize" : "10",
            "carid" : carid
        };
        $.ajax({
            type : "POST",
            url : "list1.do",
            contentType : "application/json;charset=UTF-8",
            data : JSON.stringify(data1),
            success : function(data) {
                console.log(data);
            }
        });
    }

注意:此时

contentType = “application/json;charset=UTF-8”
data =JSON.stringify(data1)

  • 后端
@RequestMapping("/list1.do")
@ResponseBody
public List<Map<String, Object>> flist1 ( @RequestBody Map mp) {  
    System.out.println(mp.get("pageindex")+",");
    System.out.println(mp.get("pagesize")+",");
    System.out.println(mp.get("carid")+",");
    //List<Map<String, Object>> list=   dao_charge.selectcharge(gets);
    List<Map<String, Object>> list=new ArrayList();
    return list;
}

用例2

  • 前端
function search2() {
    var carid = $("input[name='carid']").val();
    var data1 = {
        "pageindex" : "1",
        "pagesize" : "10",
        "carid" : carid
    };
    $.post("list2.do", data1).success(function(result) {
    });
}

注意:此时

contentType =application/x-www-form-urlencoded;charset=UTF-8
data=data1

  • 后端
@RequestMapping("/list2.do")
@ResponseBody
public List<Map<String, Object>> flist2 (HttpServletRequest req,
    String pageindex ,String pagesize,String carid  ) {      
    System.out.println(req.getParameter("pageindex")+",");
    System.out.println(req.getParameter("pagesize")+",");
    System.out.println(req.getParameter("carid")+",");
    System.out.println(",,,,,,,");
    System.out.println(pageindex+",");
    System.out.println(pagesize+",");
    System.out.println(carid+",");  
    List<Map<String, Object>> list=new ArrayList();
    return list;
}

用例3

  • 前端
function search3() {
    var carid = $("input[name='carid']").val();    
    var data1 = {
        "pageindex" : "1",
        "carid" : carid
    };  
    $.ajax({
    type : "POST",
    url : "list2.do",
    contentType : "application/x-www-form-urlencoded;charset=UTF-8",
    data : data1,
    success : function(data) {
        console.log(data);
    }
    });
}

注意: 此时

contentType =application/x-www-form-urlencoded;charset=UTF-8
data=data1
如果省略 contentType 会自动识别为application/x-www-form-urlencoded

  • 后端
    同用例2的后端写法

附3篇扩展

这三篇博文在其他方面 讲明了ajax 与springmvc 的关系,

  1. springMVC返回数据的四种方式
  2. SpringMVC的REST风格的四种请求方式
  3. SSpringMVC前台利用ajax和FormData上传文件