Ajax传递特殊字符的数据如何解决
问题描述
如下,对含有特殊字符的text进行JSON封装,通过Ajax传递,
vardata={"Id":id,"text":text};
在后台无法进行数据接收。
解决方案
将
req.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
换为:
req.setRequestHeader("Content-type",
"application/json;charset=utf-8");
后台接受数据:
//进行json数据的接收
StringBuildersb=newStringBuilder();
BufferedReaderbr=request.getReader();
char[]buff=newchar[10000];
intlen;
while((len=br.read(buff))!=-1){
sb.append(buff,0,len);
}
Stringmess=sb.toString();
//将字符串转换为JSON对象
JSONObjectjsonObject=newJSONObject(mess);
//获取其中的值
jsonObject.getInt("Id");
//含有特殊字符的文本需要先进行转码
URLDecoder.decode(jsonObject.getString("text"),"UTF-8"));
这样就可以正确的进行文本的接收啦~