Ajax前台向后台传递对象:
数据准备
将js对象或者json对象转换为json字符串在Ajax传递,在后台中再将json字符串转换为json对象,再转换为java对象或在前端和后端构造一样的数据结构,直接用application/json内容体发送。
1 var student={ 2 name:"abc", 3 age:12, 4 no:"123" 5 }; 6 7 console.log(student); 8 //将js对象转换为json字符串通过ajax传递,在后台中再将json字符串转换为json对象再转换为java对象 9 10 student = JSON.stringify(student);
Ajax:前端发送
1 $.ajax({ 2 url : url, 3 type : "POST", 4 data : { 5 sendData:"传递下面的json字符串", 6 jsonStr: student 7 }, 8 async : isAsync, 9 dataType:data_type, 10 beforeSend : beforeSendFun, 11 success : function(return_data) { 12 successFun(return_data); 13 }, 14 error : function(XMLHttpRequest, textStatus, errorThrown) { 15 alert("请求处理失败"); 16 } 17 });
后台解析:
String sendData = request.getParameter("sendData"); if (sendData.equals("传递下面json字符串")){ String jsonStr = request.getParameter("jsonStr"); JSONObject student_json= new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
Student student = (Student)JSONObject.toBean(student_json,Student.class);//再将json对象转换为Student对象 }
(1)发端是对象var abc = new { name = "菜鸟教程", site = "http://www.runoob.com" };JSON(abc)
console.log(ds);
console.log(typeof (ds));object
console.log(ds.name);菜鸟教程
Objectname: "菜鸟教程"site: "http://www.runoob.com"__proto__: Object
ThemeList.js:24 {"name":"菜鸟教程","site":"http://www.runoob.com"}
ThemeList.js:27 "{"name":"菜鸟教程","site":"http://www.runoob.com"}"
ThemeList.js:28 ""{\"name\":\"菜鸟教程\",\"site\":\"http://www.runoob.com\"}""
(2)发端是字符串 string abc= "{"name":"菜鸟教程","site":"http://www.runoob.com"}";JSON(abc)
var mm=JSON.parse(""{\"name\":\"菜鸟教程\",\"site\":\"http://www.runoob.com\"}"")
console.log(typeof (mm));string
var ll = JSON.parse(mm);object
console.log(ll.name);菜鸟教程