jsp頁
<script type="text/javascript">
$(window).load(
function dook() {
alert("start");
var datas = ({
"msg" : 'Test Message',"member":'A1234'
});
var jsonobj = JSON.stringify(datas); //JSON.stringify() javascrip 轉 Json方法
$.ajax({
data : {
para : jsonobj
},
dataType : 'json', // 接收回傳Json格式意思
url : 'Json_get.do',
type : 'POST',
success : function(ans) {
alert("OOO");
alert(ans.aaa);
alert(ans.eee);
alert(ans.ccc);
alert(ans.ddd);
alert(ans.nnn);
alert(ans.res);
alert(ans);
},
error : function() {
alert("XXX");
alert('Ajax readyState: ' + xhr.readyState + '\nstatus: '
+ xhr.status + ' ' + err);
}
});
});
</script>
後端class:
@RequestMapping("/Json_get")
public @ResponseBody
void generateReport4(HttpServletRequest request,
HttpServletResponse response) {
try {
//response
//PrintWriter outt = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
//要用這種方法格式才能傳出中文不亂數 ,我之前是用(text/json) 是錯的
JSONObject jsonObj = (JSONObject) JSONValue.parse(request
.getParameter("para"));
System.out.println(jsonObj.get("email"));
JSONObject obj = new JSONObject();
String email = (String) jsonObj.get("email");
UserService userSevice = new UserService();
memberModel member = userSevice.getUserGrid(email);
Gson aa = new Gson();
String strmebmer = aa.toJson(member);
System.out.println(strmebmer);
obj.put("jjj","hhh");
obj.put("res", "hello...");
obj.put("ccc", new String("中文".getBytes("ISO-8859-1"),"UTF-8").trim());
Map ma = new HashMap();
ma.put("jjj","hhh");
ma.put("res", "hello...");
ma.put("aaa", "中文");
ma.put("eee", "send");
ma.put("ddd", "Fhhhhh");
ma.put("nnn","卡片");
response.getWriter().write(aa.toJson(ma)); // Gson
} catch (Exception e) {
e.printStackTrace();
}
}
全站熱搜