[英]'Uncaught SyntaxError: Unexpected token u' when using JSON.parse
I'm using JSON.parse as a simple database on my computer with LocalStorage. 我在使用LocalStorage的计算机上使用JSON.parse作为一个简单的数据库。 It works smoothly until I'm doing the check of this "database"; 它工作顺利,直到我正在检查这个“数据库”; heres the code for entering information to LocalStorage: 下面是用于向LocalStorage输入信息的代码:
var users = JSON.parse(localStorage.registeredUsers);
users.push({username:name, password:userpass, connected:false});
localStorage.registeredUsers = JSON.stringify(users);
and when I', having the check of that registeredusers I get the error "Uncaught SyntaxError: Unexpected token u": 当我'检查那些注册用户时,我收到错误“Uncaught SyntaxError:Unexpected token u”:
var users = JSON.parse(localStorage.registeredUsers);
if(users[userindex].connected)
{.........}
The error points to the line with JSON.parse. 该错误指向JSON.parse行。 I tried to figure it out with some similiar topics but couldnt find the way. 我试图用一些类似的主题弄明白,但无法找到方法。
The code that I push into the array of localstorage: 我推入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');
}
Try 尝试
var users = localStorage.registeredUsers? JSON.parse(localStorage.registeredUsers) : [];
or if you don't like the ternary operator, 或者如果你不喜欢三元运算符,
var users=[];
if(localStorage.registeredUsers){
users=JSON.parse(localStorage.registeredUsers);
}
might help 可能有帮助
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
I can't identify the error's cause. 我无法确定错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.