如果前端傳遞的參數是加密過的,需要在后台解密,有中文等特殊符號需要用到加密:
前端代碼:
$.ajax({ type: "POST", url: "/init/SaveToDatabase", dataType: "json", async: false, data: decodeURIComponent(JSON.stringify(array)), success: function (result) { var statusCode = result.StatusCode; console.log(statusCode); if (statusCode == 200) { layer.msg("成功:請求已經成功..."); } else if (statusCode == 500) { layer.msg("失敗:請求失敗,請重試...") } } });
后台代碼:
1 public JSONObject saveToDatabase(String jsonArray) throws UnsupportedEncodingException { 2 //前台傳的數據是加密的,后端解密 3 jsonArray1 = URLDecoder.decode(jsonArray1, "utf-8"); 4 //踩過的坑,解密之后的數據最后一個字符多了一個=號,截取掉,endsWith判斷最后一位是否是=號 5 if (jsonArray.endsWith("=")) { 6 jsonArray = jsonArray.substring(0, jsonArray.length() - 1); 7 } 8 //轉化成json數組 9 JSONArray jsonArray = JSONArray.parseArray(jsonArray); 10 }
補充一句,后台的加密寫法:
name = URLEncoder.encode(name, "utf-8");