不同contentType下前臺傳JSON到後臺
阿新 • • 發佈:2019-02-19
【1】contentType預設為application/x-www-form-urlencoded的情況
① JSP例項如下
var url = "person.action"; var jsonStr = {"name":'ji',"age":20};//object型別 var jsonArrayFinal = JSON.stringify(jsonStr);//string型別 jQuery.ajax({ type: "post",//put delete get post url: url, //dataType : 'json', /* 預期伺服器返回的資料型別 xml html script json jsonp text ; 如果不指定,則伺服器根據返回資料型別自行判斷 */ async:true,//預設非同步 data : {mydata:jsonArrayFinal}, //或{'mydata':jsonArrayFinal} /* 要麼使用 \ 對json進行手動轉譯,要麼使用JSON.stringify(jsonStr) 將其轉換為字串型別; 如果不進行轉譯,使用【2】中的後臺接收方法,那麼不會報異常,但是獲取不到資料。 data : {mydata:jsonStr},//報空指標異常,傳不過去 */ contentType:"application/x-www-form-urlencoded",//預設值 success: function(data,textStatus){ alert(data); alert("操作成功"); }, error: function(xhr,status,errMsg){ alert("操作失敗!"); } });
② 後臺接收方法:
public String getJson(){ //引數為鍵值對方式可以直接使用getParameter方法 String jsonStr = getRequest().getParameter("mydata"); System.out.println(jsonStr); ObjectMapper objectMapper = new ObjectMapper(); try { Person person1 = objectMapper.readValue(jsonStr, Person.class); System.out.println(person1); out(jsonStr); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
result as follows :
③ F12檢視瀏覽器控制檯:
Remote Address:127.0.0.1:8080 Request URL:http://localhost:8080/JavaSE-JS/person.action Request Method:POST Status Code:200 OK Response Headers//Response Headers view source Content-Type:text/html;charset=UTF-8 Date:Wed, 18 Jan 2017 01:31:02 GMT Server:Apache-Coyote/1.1 Transfer-Encoding:chunked Request Headers//Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:zh-CN,zh;q=0.8 Connection:keep-alive Content-Length:51 //contentType Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Cookie:JSESSIONID=E7D60D8B9B3E1958B7077CE26E4EE75A Host:localhost:8080 Origin:http://localhost:8080 Referer:http://localhost:8080/JavaSE-JS/testAjax1.jsp User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 X-Requested-With:XMLHttpRequest Form Data//表單資料 view source view URL encoded mydata:{"name":"ji","age":20}
可以看到,此時請求頭,contentType為預設值,傳送資料在Form Data。
【2】contentType預設非application/x-www-form-urlencoded的情況
比如,contentType:"application/json;charset=utf-8",
此時,若使用例子一中的後臺接收方法,是接收不到資料的。
① JSP例項如下:
jQuery.ajax({
type: "post",//put delete get post
url: url,
// dataType : 'json',
//預期伺服器返回的資料型別 xml html script json jsonp text
async:true,//預設非同步
contentType:"application/json;charset=utf-8",
//data : jsonArrayFinal,
//{"name":"ji","age":20}
data : {mydata:jsonArrayFinal},
//mydata={"name":"ji","age":20}---進行了url編碼
//mydata=%7B%22name%22%3A%22ji%22%2C%22age%22%3A20%7D
//data : jsonStr,
//引數:name=ji&age=20
//data : {mydata:jsonStr},
//mydata[name]=ji&mydata[age]=20-進行了編碼-mydata%5Bname%5D=ji&mydata%5Bage%5D=20
success: function(data,textStatus){
alert(data);
alert("操作成功");
},
error: function(xhr,status,errMsg){
alert("操作失敗!");
}
});
② 後臺接收方法:
//contentType 非 application/x-www-form-urlencoded
public String getRequestPayload() throws IOException {
HttpServletRequest req = getRequest();
StringBuilder sb = new StringBuilder();
//使用getReader()方法獲取Form Data裡面資料
try(BufferedReader reader = req.getReader();) {
char[]buff = new char[1024];
int len;
while((len = reader.read(buff)) != -1) {
sb.append(buff,0, len);
}
}catch (IOException e) {
e.printStackTrace();
}
String sb2 = URLDecoder.decode(sb.toString(),"UTF-8");
/*
* 解碼前:mydata=%7B%22name%22%3A%22ji%22%2C%22age%22%3A20%7D
* 解碼後:mydata={"name":"ji","age":20}
*/
out(sb2);
System.out.println(sb2);
return null;
}
第一種情況:data : jsonStr,
,後臺獲取值name=ji&age=20
;
第二種情況:data : {mydata:jsonStr},
,後臺獲取值
進行了URL編碼:mydata%5Bname%5D=ji&mydata%5Bage%5D=20
解碼後:mydata[name]=ji&mydata[age]=20
第三種情況:data : jsonArrayFinal,
,後臺獲取值{"name":"ji","age":20}
;
第四種情況:data : {mydata:jsonArrayFinal},
,後臺獲取值
進行了URL編碼:mydata=%7B%22name%22%3A%22ji%22%2C%22age%22%3A20%7D
解碼後:mydata={"name":"ji","age":20}
③ F12檢視瀏覽器控制檯:
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/JavaSE-JS/person2.action
Request Method:POST
Status Code:200 OK
Response Headers
view source
Content-Type:text/html;charset=UTF-8
Date:Wed, 18 Jan 2017 01:43:03 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8
Connection:keep-alive
Content-Length:22
//Content-Type:application/json;charset=UTF-8
Content-Type:application/json;charset=UTF-8
Cookie:JSESSIONID=E7D60D8B9B3E1958B7077CE26E4EE75A
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/JavaSE-JS/testAjax1.jsp
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload//此時,資料在這裡 !
view source
{name: "ji", age: 20}
age: 20
name: "ji"
【3】Tips
-
若使用預設contentType,則data請使用key:value形式,且如果value為json,進行轉譯;
-
若使用自定義contentType(如application/json),則data如果使用value形式,轉譯與否看後臺接收方法;如果使用key:value形式,後臺要進行URL解碼!
-
若使用自定義contentType,第一種後臺方法是獲取不到資料的,請使用第二種後臺接收方法;
-
上面json是手動拼接,也可以可以直接獲取json如下:
var jsonStr = $('#editform').serializeArray();//JSON Object
jsonStr = JSON.stringify(queryString);//JSON string