解決backbone url請求中參數有中文,存入資料庫是亂碼 ...
最近項目用到了backbone 做前後端的分離方案,遇見了中文亂碼問題,解決方案總結如下: 假設需要存一條課程記錄到後臺 model定義如下: var AddCourse= Backbone.Model.extend({ url:path+"/course/add", parse : function(response){ return response.data; } }); encodeURIComponent 函數 將中文的內容進行編碼 $('#addCourseBtn' ).click(function(){ var courseName = encodeURIComponent($('#myCourseName').val().trim(), 'utf8'); var description = encodeURIComponent( $('#description').val().trim(),'utf8' ); var privilege = encodeURIComponent($('#privilege').val().trim(), 'utf8'); var userId=$.cookie( 'userId'); var course = new AddCourse(); //傳數據 course.fetch({data : $.param({ courseName : courseName,description : description,privilege : privilege,userId : userId})}); }); api定義,URLDecoder.decode函數進行解碼 @Controller @RequestMapping("/course") public class CourseController { @Resource private CourseService courseService; @RequestMapping("/add") //添加代碼:編碼修改 @ResponseBody public Result add(String courseName,String description,String privilege,int userId){ String deCourseName; String deDescription; String dePrivilege; Result result =new Result(); try { deCourseName = URLDecoder.decode(courseName, "UTF-8"); deDescription = URLDecoder.decode(description, "UTF-8"); dePrivilege = URLDecoder.decode(privilege, "UTF-8"); result=courseService.addCourse(deCourseName, deDescription, dePrivilege, userId); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }