最近项目用到了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;
}