ff上报错是:SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data
前端代码
ChatMassage cm = ChatMassage.instance();
String mas = cm.getMassage(num);
int massageNumber = ChatMassage.mass_num;
System.out.println("mnumber:"+massageNumber);
session.setAttribute("massageNumber", massageNumber);
JSONObject json = new JSONObject();
json.put("massage", mas);
json.put("massageNumber", massageNumber);
System.out.println(json);
return json;
前端问题
function loadMassage(){
$.ajax({
data: "num=" + massageNumber,
url: "loadData.do",
Success: $(function(msg){
var res =$.parseJSON(msg);
alert(parseInt(res.massageNumber));
massageNumber=parseInt(res.massageNumber);
massages+=res.massgae;
document.body.innerHTML=massages;
})
});
json生成部分
} else {
cm.addUser(name);
HttpSession session = request.getSession();
session.setAttribute("username", name);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String data = dateFormat.format(new Date());
cm.setMassage("<br><font color=\'red\'> welcom "+name+" join in chatting" + " at "+data+"</font><br>");
}
request header:
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8080/spring/chat
X-Requested-With: XMLHttpRequest
Cookie: JSESSIONID=26FBFB1DFC7729A3E1A423AECA8B2995
DNT: 1
Connection: keep-alive
Response Header:
Server: Apache-Coyote/1.1
Content-Type: : application/json
Content-Length: 108
Date: Mon, 25 Dec 2017 16:33:01 GMT
在返回时已设置编码
Object result = action.execute(request, response);
if(result instanceof String)
{
request.getRequestDispatcher(result.toString()).forward(request, response);
} else if (result instanceof JSONObject) {
response.setHeader("Content-Type:", "application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print((JSONObject)result);
}
因为是 Linux 系统,所以一般情况下不会出现编码问题。并且我也将中文全部替换为英文。
之前在没开 debug 时,解析全部为 undefinded