ztree通過ajax載入json資料中文亂碼的解決方法:springmvc配置
阿新 • • 發佈:2019-01-17
一、問題描述
使用zTree的非同步重新整理父級選單時,伺服器返回中文亂碼,但專案中使用了SpringMvc,已經對中文亂碼處理,為什麼還會出現呢?
此處為的非同步請求的配置:
Java程式碼- async: {
- enable: true,
- url: basePath + '/sysMenu/listSysMenu',
- autoParam: ["id=parentId"]
- }
SpringMvc中文字元處理:
Java程式碼- <mvc:annotation-driven>
- <mvc:message-converters>
- <bean class="org.springframework.http.converter.StringHttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>application/json;charset=UTF-8</value>
-
<value>text/html;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
返回的結果有中文亂碼:
Js程式碼- [
- {
- "menuId": "880095098165986816",
- "menuName": "????",
- "parentId": "880095098165986815",
-
"menuUrl": "http://localhost:8080/imovie-manage/sysMenu/listSysMenuUI",
- "menuIcon": "",
- "menuSort": 1,
- "isEnable": 1,
- "parentMenuName": "??",
- "id": "880095098165986816",
- "name": "????",
- "pId": "880095098165986815"
- },
- {
- "menuId": "880095098165986817",
- "menuName": "???????",
- "parentId": "880095098165986815",
- "menuUrl": "http://localhost:8080/imovie-manage/sysMenu/treeSysMenuUI",
- "menuIcon": "",
- "menuSort": 1,
- "isEnable": 1,
- "parentMenuName": "??",
- "id": "880095098165986817",
- "name": "???????",
- "pId": "880095098165986815"
- }
- ]
二、解決方案
經過排查,發現是SpringMvc中文字元處理的supportedMediaTypes少了一種型別。
從瀏覽器傳送的請求來看:
非同步重新整理使用的是post請求,但從伺服器返回的時候,Content-Type為:text/plain;charset=ISO-8859-1
charset是ISO-8859-1,而不是UTF-8,而SpringMvc處理的中文亂碼沒有包含這種型別,所以導致中文亂碼。
所以最後的解決方法是在SpringMvc中文處理加上text/plain這個型別,如下:
Java程式碼- <value>text/plain;charset=UTF-8</value>
具體如下:
Java程式碼- <property name="supportedMediaTypes">
- <list>
- <value>application/json;charset=UTF-8</value>
- <value>text/html;charset=UTF-8</value>
- <value>text/plain;charset=UTF-8</value>
- </list>
- </property>
然後問題就這樣解決了。^_^