2013-07-23 49 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')在那裏,這意味着唯一的問題是它無法找到輸入值。有時外部庫會阻止隱藏元素的輸入。剝離除您向我們展示的代碼之外的所有內容的頁面,然後嘗試添加您已逐一添加的其他庫,直至找到問題。

相關問題