JSON.parse 导致“未捕获的语法错误:意外的令牌 u”
JSON.parse causes "Uncaught SyntaxError: Unexpected token u"
我有:
<input type="hidden" id="notifications" value="@ViewBag.Notifications" />
当我在此行上放置断点并检查值时,我看到该值为:
[{"id":"42647","isRead":0,"MessageType":3},{"id":"fsh3hg","isRead":0,"MessageType":2}]
我想在页面加载时在 JavaScript 中解析这个值,所以我写了:
var notifications = document.getElementById('notifications').value;
alert(notifications); // it prints undefined
alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement
var parsedNotifications;
if (notifications != '') {
parsedNotifications = JSON.parse(notifications);
}
但我在以下行收到错误"未捕获的语法错误:意外的令牌u":
parsedNotifications = JSON.parse(notifications);
为什么会发生此错误?
你写道:
alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement
在评论中,HtmlSpanElement
是出现问题的线索。显然,您的页面有一个<span>
,其id
与隐藏<input>
相同,因此document.getElementById
找到错误的元素,并且value
返回undefined
,因为<span>
没有值。
将<span>
id
更改为"通知"以外的内容,您的代码应该可以工作。
所以我们知道document.getElementById('notifications'(在那里,这意味着唯一的问题是它找不到输入值。 有时外部库会阻止隐藏元素的输入。 剥离您的页面中除您向我们展示的代码之外的所有内容,然后尝试逐个添加您包含的其他库,直到找到问题所在。
相关文章:
- 铬:“;未捕获的语法错误:意外的标记:"
- Javascript未捕获语法错误意外的标识符错误
- 未捕获的语法错误:意外的标记{
- "未捕获的语法错误:意外的标记}"
- eslint:“;分析错误:意外的“”标记;
- 未捕获的语法错误:意外的令牌,
- "未捕获的语法错误:意外的标记"角度JS
- "未捕获的语法错误:意外的标记<"当尝试使用谷歌'核心报告API
- NodeJS用Multer上传图片;错误:意外字段“”;
- 在一个函数中,我有一个未捕获的语法错误:意外的标记else
- data.php:1未捕获的语法错误:意外的令牌:
- 未捕获的语法错误:意外的令牌非法?看起来不错
- 未捕获的语法错误:意外的标记<在yii
- AngularJS $http GET 请求到本地 JSON 文件返回语法错误:意外令牌]
- 未捕获的语法错误:意外的令牌 = (Chrome)
- Sencha 2.0 和 Codeigniter RESTful API 生成未捕获的语法错误:意外令牌:
- “语法错误:意外的令牌)”在 javascript 调用中,当 eval(value) 为空时
- HTML 无法识别我要求它运行的 javascript 文件,语法错误:意外的令牌“<”(匿名函数)script.js:
- 未捕获的语法错误:意外的令牌 if
- 使用 JSON.parse 将字符串(变量)转换为对象,错误意外标记