昨天遇見一個問題,系統採用的是先後端分離的設計,前端使用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; } );