springmvc+jsp中关于JQuery ajax提交的Content-Type参数设置application/json和application/x-www-form-urlencoded区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq32933432/article/details/80817250

介绍

本人页面是用的JSP,后台用的Spring MVC。

使用JQ的ajax需要设置Content-Type,Content-Type的设置有以下几种常用的

"Content-Type": "application/x-www-form-urlencoded" // 适用于大部分情况
"Content-Type": "application/json"      //适用于复杂JSON数据的提交
"Content-Type": "multipart/form-data"   // 适用于文件上传

下面来逐一介绍

application/x-www-form-urlencoded

application/x-www-form-urlencoded是jq ajax默认的提交方式,当不写contentType时即是此种方式,代表使用表单形式提交。
JSP:

$.ajax({
   type: "POST",
   url: "${webRoot}/ggzy/ggzyZhzfkController.do?flfgNameQuery",
   contentType: "application/x-www-form-urlencoded", 
   dataType: "json", //表示返回值类型,不必须
   data: {ids: '1'},
   success: function (jsonResult) {
       alert(jsonResult);
   }
});

后台:

public AjaxJson flfgNameQuery(String ids,HttpServletRequest req) {
        String ids1 = req.getParameter("ids");
        System.out.println(ids);   //输出1
        System.out.println(ids1);  //输出1
}

application/json

使用application/x-www-form-urlencoded只能提交简单类型的json数据,当json数据很复杂时就须要使用application/json。

JSP:

$.ajax({
    type: "POST",
    url: "${webRoot}/ggzy/ggzyZhzfkController.do?flfgNameQuery",
    contentType: "application/json", //必须有
    dataType: "json", //表示返回值类型,不必须
    data: JSON.stringify({'ids': '1'}),
    success: function (jsonResult) {
        alert(jsonResult);
    }
});

后台

public AjaxJson flfgNameQuery(@RequestBody entry et,HttpServletRequest req) {
        String str = req.getParameter("ids");
        System.out.println(str);      //输出null
        System.out.println(et.getIds())//输出1
}

public class entry {
    String ids;

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }
}

也可以使用JSONObject

public AjaxJson flfgNameQuery(@RequestBody JSONObject object,HttpServletRequest req) {
        String str = req.getParameter("ids");
        System.out.println(str);      //输出null
        System.out.println(object.getXXX())//输出1
}

总结:

当使用application/x-www-form-urlencoded时其实JSP会默认把我们的json数据认为是一个对象,而使用application/json时需要向后台传入一个JSON字符串,所以要用JSON.stringify函数把JSON对象转成json字符串。

猜你喜欢

转载自blog.csdn.net/qq32933432/article/details/80817250