我的登录页面出现Uncaught SyntaxError: Unexpected token u
错误。我正在使用angularjs和localstorage。
HTML
<div class="login-body">
<div class="container">
<div class="col-lg-8 col-md-8 col-sm-8 col-lg-offset-4 col-md-offset-4 col-sm-offset-4">
<form class="form-horizontal" name="LoginForm">
<div class="form-group">
<div class="col-lg-6 col-md-6 col-sm-6">
<input type="text" class="ejinputtext input-field col-sm-12 col-md-12 col-lg-12" ng-model="user.username" name="UserName" placeholder="Username" style="margin-bottom: 15px; margin-top: 30px;" required/>
</div>
<span class="error" ng-show="$root.submitted && Loginform.UserName.$error.required">Enter Username!</span>
</div>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-sm-6">
<input type="password" class="ejinputtext input-field col-sm-12 col-md-12 col-lg-12" ng-model="user.password" placeholder="Password" name="Password" required />
</div>
<span class="error" ng-show="$root.submitted && Loginform.Password.$error.required">Enter Password!</span>
</div>
<div class="checkbox">
<label style="padding-left:0px">
<input type="checkbox" ej-checkbox e-size= "small" >
Remember me</label>
</div>
<br />
<div class="form-group text-center">
<div class="col-lg-6 col-md-6 col-sm-6">
<button ej-button e-size= "large" ng-click="login(user)">Log in</button>
</div>
</div>
<div class="form-group text-center">
<div class="col-lg-6 col-md-6 col-sm-6">
<a href="ForgetPassword.html">Request new password</a>
</div>
</div>
</form>
</div>
</div>
</div>
的JavaScript
var app = angular.module('HRApp.controllers', ['ngStorage']);
app.controller('LoginController', function ($scope, $localStorage, $location) {
$scope.user = {
username: "",
password: "",
};
var list = JSON.parse(localStorage.getItem('user'));
if (list != undefined && list != '') {
$scope.user = list;
}
$scope.login = function (user) {
$scope.user.username = user.username;
$scope.user.password = user.password;
localStorage.setItem('Login Details', JSON.stringify($scope.user));
var path = "layout.html";
location.replace(path);
};
});
如何解决此问题?
答案 0 :(得分:1)
当JSON.parse
的值实际为undefined
时,通常会看到该错误。
因此,在JSON.parse
上致电localStorage.getItem("user")
之前,请检查其真实价值。
var list = $localStorage.getItem('user') ? JSON.parse($localStorage.getItem('user')) : undefined;
一些建议:
在您的HTML
中,ng-model
字段使用了input
。
因此,您无需将user
对象传递给login
方法。默认情况下,值将设置为$scope.user.username
和$scope.user.password
。
因此您的login
方法将成为:
$scope.login = function (user) {
$localStorage.setItem('Login Details', JSON.stringify($scope.user));
// make sure it should be Login Details / user
var path = "layout.html";
$location.replace(path);
};
问题在于localStorage.getItem("user")
。我没有看到你设置localStorage.setItem("user")
的任何地方。即使在登录方法中,您也有localStorage.setItem("Login Details")
。
答案 1 :(得分:0)
您使用变量localStorage
代替$localStorage
。解决这个问题,告诉我们你是否有错误。
与location
var相同的问题(必须是$location
)。