报错SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
·
错误

错误代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
var a = {
"flag": true
};
console.log("JSON.parse(a) -> " + JSON.parse(a));
console.log("JSON.stringify(JSON.parse(a)) -> " + JSON.stringify(JSON.parse(a)));
</script>
</body>
</html>
原因
JSON.parse()方法是将一个JSON格式的字符串转换成JavaScript对象,但是在上述代码中已经是一个JavaScript对象了,如果再使用JSON.parse()方法就会报错。
JSON.stringify()方法是将一个JavaScript对象转换成符合JSON格式的字符串。
解决
正确使用JSON方法,注意数据是JavaScript对象还是字符串。
正确代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
var a = "{\"flag\": true}";
console.log("JSON.parse(a) -> " + JSON.parse(a));
console.log("JSON.stringify(JSON.parse(a)) -> " + JSON.stringify(JSON.parse(a)));
</script>
</body>
</html>
输出:

注意
Gson gson=new Gson();
String s = gson.toJson(ri);
response.setContentType("application/json;charset=utf-8");
response.getWriter().println(s);
在使用Gson中传到前端的字符串到前端就是JavaScript对象了。
success: function (data) {
var responseData = JSON.parse(data);
if (responseData.flag) {
window.location.href = "/jsp/student/system_menu.jsp";
}
},
所以上述代码才会报错。
直接调用数据即可。
success: function (data) {
if (data.flag) {
window.location.href = "/jsp/student/system_menu.jsp";
}
},
适用于现代 C++ 的 JSON。
最近提交(Master分支:2 个月前 )
960b763e
4 个月前
8c391e04
7 个月前
更多推荐

所有评论(0)