最近项目用到了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 {@Resourceprivate CourseService courseService;@RequestMapping("/add")//添加代码:编码修改@ResponseBodypublic 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 blocke.printStackTrace();}return result;}
以上所述是小编给大家介绍的关于backbone url请求中参数带有中文存入数据库是乱码的快速解决办法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!
新闻热点
疑难解答