关于Ajax传输字符串到后台呈中文乱码的解决方法
框架:springboot+maven+Mybatis
使用软件:Intellij IDEA 2018.2.6
前端:jquery-1.11.3.min.js
问题:在使用Ajax传输一个字符串的时候,前台显示出中文字样,后台却是乱码+“=”,尝试了“produces = "text/html;charset=utf-8"”,无果:
<input type="text" id="uid"/>
<div id="message"></div>
</body>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$("#uid").blur(function () {
var uid = $(this).val();
// var uid = encodeURI($('#uid').val(),"utf-8");
// data = {"goods_name":uid};
$.ajax({
url:"/async",
data:uid,
type:"POST",
ContentType:"application/x-www-form-urlencoded;charset=UTF-8",
success:function (data) {
alert("返回结果集="+data)
}
})
})
</script>
解决方法:
在controller层,使用URLDecoder.decode()对乱码进行解码,用substring除去最后的“=”:
import java.io.IOException;
import java.net.URLDecoder;
public List<Map<String,Object>> async(@RequestBody String word) throws ExecutionException, InterruptedException, IOException {
MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
String goods_name = URLDecoder.decode(word, "UTF-8");
paramMap.add("goods_name", goods_name.substring(0,goods_name.length()-1));
这里转发两个网址,分别详细讲解了“使用 URLDecoder 和 URLEncoder 对中文字符进行编码和解码” 和 “substring常用的两种方法”:
https://blog.csdn.net/justloveyou_/article/details/57156039
https://blog.csdn.net/hehuihh/article/details/79033047
|