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