Recently, the project used backbone as a separation solution for the front and back ends. I encountered the problem of Chinese garbled code. The solution is summarized as follows:
Suppose you need to save a course record to the background
The model is defined as follows:
var AddCourse= Backbone.Model.extend({url:path+"/course/add",parse : function(response){return response.data;}});The encodeURIComponent function encodes Chinese content
$('#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();//Transfer data course.fetch({data: $.param({ courseName: courseName,description: description,privilege: privilege,userId: userId})});});Decode the api definition, URLDecoder.decode function for decoding
@Controller@RequestMapping("/course")public class CourseController {@Resourceprivate CourseService courseService;@RequestMapping("/add")//Add code: Encoding modification @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;}The above is a quick solution to the parameters in the backbone url request with Chinese stored in the database. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!