2013-07-23 47 views
0

我:JSON.parse会导致“未捕获的SyntaxError:意外的标记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); 
} 

,但我得到的错误“未捕获的SyntaxError:U在下面的行上有“nexpected token u”:

parsedNotifications = JSON.parse(notifications); 

为什么会发生此错误?

+0

'undefined'是无效的JSON。什么是生成的来源? – SLaks

+0

这是一个类的列表.. –

+0

该值未被正确输出。这里是一个值正确的小提琴和它正在工作:http://jsfiddle.net/A5Kf7/ –

回答

4

您写道:

alert(document.getElementById('notifications')); // it prints: Object HtmlSpanElement 

在评论,HtmlSpanElement是一个线索,什么是错的。显然,你的页面有一个<span>id相同为你隐藏<input>的,所以document.getElementById发现错误的元素,并value回报undefined因为<span>不具有价值。

<span>id更改为“通知”以外的内容,并且您的代码应该有效。

0

所以我们知道document.getElementById('notifications')在那里,这意味着唯一的问题是它无法找到输入值。有时外部库会阻止隐藏元素的输入。剥离除您向我们展示的代码之外的所有内容的页面,然后尝试添加您已逐一添加的其他库,直至找到问题。

相关问题