昨天遇见一个问题,系统采用的是先后端分离的设计,前端使用vue,elementui,后端使用java,而前端调用后端接口有两种写法,一种是jquery的ajax去跨域访问java接口,另外一种是使用vue-resource去访问接口得到数据,而jquery的ajax会有一个问题,那就是在返回数据后去调用elementUI相关的this.$notify相关以及this.function去调用在vue>methods中定义的函数,会出现函数不识别的问题,因此启用jquery的ajax改用vue-resource,可是这个在访问后端的时候,会出现传送中文乱码的问题,在vue-resource的请求参数中添加,并无改变这种状况,因此想到一个方法,在后端去改变header的CharacterEncoding,正好能够和跨域的拦截器函数放在一块儿,完整代码html
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //System.out.println("setheader"); HttpServletResponse res = (HttpServletResponse) response; res.setContentType("text/html;charset=UTF-8"); res.setHeader("Content-type", "text/html;charset=UTF-8"); res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); res.setHeader("Access-Control-Max-Age", "0"); res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("XDomainRequestAllowed","1"); request.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); }
this.$http.post( posturl, parms ).then( function(res){ //成功的处理 if(res.data.status == "OK"){ this.loading = false; this.$notify({duration: 1000, title: '成功', message: '保存成功!', type: 'success',position: 'bottom-right'}); this.go(this.pagenumber); }else{ this.$notify({duration: 1000, title: '失败', message: '保存失败!', type: 'error',position: 'bottom-right'}); } this.loading = false; }, function(res){ //失败的处理 this.loading = false; } );