浏览器向服务器发送一个点赞的异步请求,前端控制台报错
报错完整信息如下:
VM808:1 Uncaught SyntaxError: "[object Object]" is not valid JSON
at Function.parse [as parseJSON] (
at Object.success (discuss.js:7:22)
at u (jquery-3.3.1.min.js:2:27457)
at Object.fireWith [as resolveWith] (jquery-3.3.1.min.js:2:28202)
at k (jquery-3.3.1.min.js:2:77651)
at XMLHttpRequest.
(anonymous) @ discuss.js:7
u @ jquery-3.3.1.min.js:2
fireWith @ jquery-3.3.1.min.js:2
k @ jquery-3.3.1.min.js:2
(anonymous) @ jquery-3.3.1.min.js:2
load (async)
send @ jquery-3.3.1.min.js:2
ajax @ jquery-3.3.1.min.js:2
w.
like @ discuss.js:3
onclick @ 275:117
以上报错信息,可以看出是服务器端响应给浏览器的是一个无效的JSON格式的数据(我不理解为什么会无效,在网上查阅了其他网友的方法,但都没找到有很好的解决方案)
String xRequestedWith = request.getHeader("x-requested-with");
if("XMLHttpRequest".equals(xRequestedWith)){
// 异步请求
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(CommunityUtil.getJSONString(403, "您还没有登录!"));
}else{
// 普通请求
response.sendRedirect(request.getContextPath() + "/login");
}
以下是CommunityUtil.getJSONString()生成JSON数据的方法
public static String getJSONString(int code, String msg, Map
JSONObject json = new JSONObject();
json.put("code", code);
json.put("msg", msg);
if(map != null){
// 遍历map集合,每次遍历得到一个key
for(String key : map.keySet()){
json.put(key, map.get(key));
}
}
return json.toJSONString();
}
public static String getJSONString(int code, String msg){
return getJSONString(code, msg, null);
}
解决办法:把response.setContentType("application/json;charset=UTF-8")改为response.setContentType("application/plain;charset=UTF-8")返回普通文本就没有Uncaught SyntaxError: "[object Object]" is not valid JSON
response.setContentType("application/plain;charset=UTF-8");
response.getWriter().write(CommunityUtil.getJSONString(403, "您还没有登录!"));
好文推荐
发表评论