2013-11-24 87 views
7

我使用JSON.parse作爲我的計算機上的簡單數據庫與LocalStorage。 它工作順利,直到我做這個「數據庫」的檢查; 繼承人用於輸入信息的localStorage代碼:'Uncaught SyntaxError:Unexpected token u'when using JSON.parse

var users = JSON.parse(localStorage.registeredUsers); 
users.push({username:name, password:userpass, connected:false}); 
localStorage.registeredUsers = JSON.stringify(users); 

,當我」,具有該檢查registeredusers我得到的錯誤‘未捕獲的SyntaxError:意外的標記U’:

var users = JSON.parse(localStorage.registeredUsers); 
     if(users[userindex].connected) 
     {.........} 

錯誤指向帶有JSON.parse的行。 我試圖找出一些類似的主題,但無法找到方法。

,我推入的localStorage的數組代碼:

function regBtn(event) 
    { 
     event.preventDefault(); 
     name=document.forms["regform"]["username"].value; 
     userpass=document.forms["regform"]["password"].value; 
     localStorage.username=name; 
     localStorage.password=userpass; 
     if(!(localStorage.registeredUsers)) 
     { 
      localStorage.registeredUsers = '[]'; 
     } 
     var users = JSON.parse(localStorage.registeredUsers); 
     users.push({username:name, password:userpass, connected:false}); 
     localStorage.registeredUsers = JSON.stringify(users); 
     $('#mainContent').load('HomePage.html');   
    } 
+3

一個片段fom的具體json會在這裏有所幫助... – nozzleman

+1

放在一個'console.log(localStorage.registeredUsers)'就在問題行之前,並告訴我們你得到什麼...... – nnnnnn

+1

根據這個所謂的「問題(http://stackoverflow.com/a/13022566/1776367)'localStorage,registeredUsers' migth實際上未定義... – nozzleman

回答

7

嘗試

var users = localStorage.registeredUsers? JSON.parse(localStorage.registeredUsers) : []; 

,或者如果你不喜歡的三元運算符,

var users=[]; 
if(localStorage.registeredUsers){ 
    users=JSON.parse(localStorage.registeredUsers); 
} 

可能有幫助

0
function setCookies(){ 
     var cookiesObjects = {}; 
     cookiesObjects.name = document.getElementById('usr').value; 
     cookiesObjects.email = document.getElementById('email').value; 
     cookiesObjects.age = document.getElementById('age').value; 

     var actualString = JSON.stringify(cookiesObjects); 


     document.cookie = "user="+ actualString; 



    } 
    function getCookies(){ 
     var nameValueArray = document.cookie.split("="); 
     var cookieObject = JSON.parse(nameValueArray[1]); 
     document.getElementById('usr').value=cookieObject.name; 
     document.getElementById('email').value=cookieObject.email; 

     document.getElementById('age').value=cookieObject.age; 



    } 
    function clearCookies(){ 
     document.getElementById('usr').value= ""; 
     document.getElementById('email').value= ""; 
     document.getElementById('age').value= ""; 
    } 
and saying Error : Uncaught SyntaxError: Unexpected token u 

我無法確定錯誤的原因。

相關問題