最近項目用到了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; }
以上所述是小編給大家介紹的關於backbone url請求中參數帶有中文存入數據庫是亂碼的快速解決辦法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!