我有:
<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);
}
但我在以下行中收到错误“未捕获的SyntaxError:意外的令牌u”:
parsedNotifications = JSON.parse(notifications);
为什么会发生此错误?
最佳答案
你写了:
alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement
在注释中,
HtmlSpanElement
是出现问题的线索。显然,您的页面有一个<span>
,其id
与隐藏的<input>
相同,因此document.getElementById
找到错误的元素,并且value
返回undefined
,因为<span>
不会有一个价值。将
id
的<span>
更改为除“ notifications”以外的其他内容,您的代码应该可以正常工作。