javascript - JSON.parse 导致 "Uncaught SyntaxError: Unexpected token u"

标签 javascript asp.net-mvc json parsing

我有:

<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/

相关文章:

javascript - 获取在 Angular 范围内显示的新名称

javascript - 我需要帮助将重复性任务转化为递归函数 Javascript

javascript - Bootstrap Carousel 中的项目数返回 0

javascript - 如何修复 Fotorama 中图像之间的滞后?

c# - 如何在 C# 中安全地存储加密 key

asp.net-mvc - "No element in the source document matches..."(NuGet安装错误)

javascript - 如何根据表单数据重定向到页面?

.net - Azure Blob 存储作为网站图像源

c# - 在 asp.mvc 和 json 中将枚举作为字符串返回

嵌套 JSON 对象的 Jsonpath