AJAX - 前台傳JSON到后台


【1】contentType默認為application/x-www-form-urlencoded的情況

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("操作失敗!");
}
});

后台接收方法:
使用jacksonJSON框架-Jackson
http://blog.csdn.net/j080624/article/details/53395967

public String getJson(){

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",

此時,若使用例子一中的后台接收方法,是接收不到數據的。具體原因請看;post請求參數data的不同形式
http://blog.csdn.net/j080624/article/details/54598745

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();
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

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com