前台ajax代码如下:
for (var key in map) {
alert("size of map:" + Object.keys(map).length);
alert("map["+key+"]:"+ map[key]);
}
alert("转化:" + JSON.stringify(map));
$.ajax({
type:"post",
url : "updateScene.do",
data:{map:JSON.stringify(map)},
dataType:"json",
success:function (data) {
//$("body").unmask();
alert("data:" + data);
if (data == true) {
alert("保存成功!");
//window.location.reload(true);
} else {
alert("保存失败!");
}
}
})
后台servlet接收JSON字符串并解析成JAVA的Map数据类型:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8"); //让浏览器知道响应的格式和怎样处理
System.out.println("进入保存");
String jsonStr = "";
jsonStr = request.getParameter("map");
System.out.println(jsonStr);
Map<String, String> map = new HashMap<String, String>();
map = JSONObject.fromObject(jsonStr);
System.out.println("map的大小" + map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
PrintWriter out = response.getWriter();
out.println(true);
out.flush();
out.close();
}
希望有需要的朋友可以看看。