ajax將前臺的Map型別資料傳到Servlet並解析的方法。
阿新 • • 發佈:2019-01-24
前臺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(); }
希望有需要的朋友可以看看。