問題描述
如下,對含有特殊字符的text進行JSON封裝,通過Ajax傳遞,
var data = {"Id": id, "text": text};
在後臺無法進行數據接收。
解決方案
將req.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
換爲:
req.setRequestHeader("Content-type",
"application/json; charset=utf-8");
後臺接受數據:
//進行json數據的接收
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
char[] buff = new char[10000];
int len;
while((len = br.read(buff)) != -1){
sb.append(buff, 0, len);
}
String mess = sb.toString();
//將字符串轉換爲JSON對象
JSONObject jsonObject=new JSONObject(mess);
//獲取其中的值
jsonObject.getInt("Id");
//含有特殊字符的文本需要先進行轉碼
URLDecoder.decode(jsonObject.getString("text"), "UTF-8"));
這樣就可以正確的進行文本的接收啦~