使用JSON.parse时,'未捕获的SyntaxError:意外的标记u'

时间:2013-11-24 10:11:26

标签: javascript jquery json

我在使用LocalStorage的计算机上使用JSON.parse作为简单数据库。 它工作顺利,直到我正在检查这个“数据库”; 下面是用于向LocalStorage输入信息的代码:

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

当我'检查那些注册用户时,我收到错误“Uncaught SyntaxError:Unexpected token 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');        
    }

2 个答案:

答案 0 :(得分:7)

尝试

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

或者如果您不喜欢三元运算符,

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

可能有帮助

答案 1 :(得分: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

我无法确定错误的原因。