我有:
<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);
}
但我在以下行收到错误“Uncaught SyntaxError: Unexpected token u”:
parsedNotifications = JSON.parse(notifications);
为什么会出现这个错误?
最佳答案
你写道:
alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement
在评论中,HtmlSpanElement
是出现问题的线索。显然,您的页面有 <span>
谁的id
与您隐藏的 <input>
相同 ,所以document.getElementById
找到错误的元素,并且 value
返回undefined
因为<span>
没有值。
更改 id
<span>
的除了“通知”之外,您的代码应该可以工作。
关于javascript - JSON.parse 导致 "Uncaught SyntaxError: Unexpected token u",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17818033/