Мне нужна помощь от вас. Можешь направить меня, пожалуйста?
Я использую JSON в качестве учетных записей данных. Но мне нужно создать сеанс с куки.
Дело в том, что когда я успешно вошел в систему, cookie был создан, но был создан только пользователь, под которым я вошел в систему. Не все объекты в данных JSON.
Файл JSON:
{ "users": [{
"id": 1,
"first_name": "John",
"last_name": "Doe",
"email": "[email protected]",
"username": "john20",
"password": "doe20"
},
{
"id": 2,
"first_name": "Julia",
"last_name": "Chan",
"email": "[email protected]",
"username": "julia19",
"password": "chan19"
}
]
}
Поэтому, когда я войду в систему с именем пользователя julia19 с настоящим паролем, я войду в систему, и будет создан файл cookie с полной информацией об имени пользователя julia19 (id, имя, фамилия, адрес электронной почты, имя пользователя, пароль) .
я использую
document.cookie = JSON.stringify(jcontent);
но он показывает все объекты в файле JSON.
Полный файл:
var ajaxhttp = new XMLHttpRequest();
var url = "./data/accounts.json";
ajaxhttp.open("GET", url, true);
ajaxhttp.setRequestHeader("content-type","application/json");
ajaxhttp.onreadystatechange = function () {
if (ajaxhttp.readyState == 4 && ajaxhttp.status == 200) {
var jcontent = JSON.parse(ajaxhttp.responseText);
document.addEventListener("submit", validateForm);
function validateForm(e) {
let uName = document.getElementById("username").value;
let pWord = document.getElementById("password").value;
if (jcontent.users.find(r => r.username == uName && r.password == pWord)) {
document.cookie = JSON.stringify(jcontent);
alert("Successfully login!")
}
else {
e.preventDefault()
alert("Username or Password is wrong!");
}
}
}
}
ajaxhttp.send(null);
//Focus Field
document.querySelector("#username").focus();
// //Keypress
document.getElementById("username").addEventListener("keypress", keyUsr);
document.getElementById("password").addEventListener("keypress", keyPass);
function keyUsr(u) {
if (u.keyCode === 32) {
alert ("Space keys are not allowed");
document.getElementById("username").value = "";
}
}
function keyPass(p) {
if (p.keyCode === 32) {
alert ("Space keys are not allowed");
document.getElementById("password").value = "";
}
}
@import url(https://fonts.googleapis.com/css?family=Raleway:400,100,200,300);
* {
margin: 0;
padding: 0; }
center {
margin-top: 70px;
margin-bottom: -40px;
}
.wrapper {
width: 340px; padding: 20px;
margin: 0 auto;
}
a {
color: #666;
text-decoration: none;
}
a:hover {
color: #4FDA8C; }
input { font: 16px/26px "Raleway", sans-serif; }
body {
background-color: #f1f2f2;
font: 16px/26px "Raleway", sans-serif;
text-align: center;
-webkit-font-smoothing: antialiased;
background: white;
color: black;}
.form-wrap {
background-color: #fff;
width: 320px;
margin: 3em auto;
box-shadow: 0px 1px 8px #BEBEBE;
-webkit-box-shadow: 0px 1px 8px #BEBEBE;
-moz-box-shadow: 0px 1px 8px #BEBEBE;
}
.form-wrap .tabs { overflow: hidden; }
.form-wrap .tabs h3 {
float: left;
width: 50%;
}
.form-wrap .tabs h3 a {
padding: 0.5em 0;
text-align: center;
font-weight: 400;
background-color: #e6e7e8;
display: block;
color: #666;
}
.form-wrap .tabs h3 a.active { background-color: #fff; }
.form-wrap .tabs-content { padding: 1.5em; }
.form-wrap .tabs-content div[id$ = "tab-content"] { display: none; }
.form-wrap .tabs-content .active { display: block !important; }
.form-wrap form .input {
box-sizing: border-box;
-moz-box-sizing: border-box;
color: inherit;
font-family: inherit;
padding: .8em 0 10px .8em;
border: 1px solid #CFCFCF;
outline: 0;
display: inline-block;
margin: 0 0 .8em 0;
padding-right: 2em;
width: 100%;
}
.form-wrap form .button {
width: 100%;
padding: .8em 0 10px .8em;
background-color: #28A55F;
border: none;
color: #fff;
cursor: pointer;
text-transform: uppercase;
}
.form-wrap form .button:hover { background-color: #4FDA8C; }
.form-wrap form .checkbox {
visibility: hidden;
padding: 20px;
margin: .5em 0 1.5em;
}
.form-wrap form .checkbox:checked + label:after {
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
filter: alpha(opacity=100);
opacity: 1;
}
.form-wrap form label[for] {
position: relative;
padding-left: 20px;
cursor: pointer;
}
.form-wrap form label[for]:before {
content: '';
position: absolute;
border: 1px solid #CFCFCF;
width: 17px;
height: 17px;
top: 0px;
left: -14px;
}
.form-wrap form label[for]:after {
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
opacity: 0;
content: '';
position: absolute;
width: 9px;
height: 5px;
background-color: transparent;
top: 4px;
left: -10px;
border: 3px solid #28A55F;
border-top: none;
border-right: none;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
transform: rotate(-45deg);
}
.form-wrap .help-text { margin-top: .6em; }
.form-wrap .help-text p {
text-align: center;
font-size: 14px;
}
.text-logo {
font-weight: 700;
font-family: "Archivo", sans-serif!important;
color: var(--black)!important;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8" />
<meta name = "viewport" content = "width=device-width, initial-scale=1.0" />
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<!-- Google Fonts -->
<link href = "https://fonts.googleapis.com/css2?family=Archivo:wght@400;700&display=swap" rel = "stylesheet" />
<!-- Custom StyleSheet -->
<link rel = "stylesheet" href = "styles/form-login.css" />
<title>Onbena Shop</title>
</head>
<body>
<div class = "wrapper">
<h1 class = "text-logo">ONBENA SHOP</h1>
<h2><b>Login</b></h2>
<p>You need to login before access it</p>
<form method = "post" id = "login">
<div class = "form-group">
<label>Username</label>
<input type = "text" id = "username" name = "username" class = "form-control">
<span id = "help-error"></span>
</div>
<div class = "form-group">
<label>Password</label>
<input type = "password" id = "password" name = "password" class = "form-control">
<span id = "help-error"></span>
</div>
<div class = "form-group">
<input type = "submit" id = "button" class = "btn btn-primary" value = "Login" onclick = "addCookie()">
<a href = "./" class = "btn btn-primary">Cancel</a>
</div>
<p>Don't have an account? <a href = "register.html">Sign up now</a>.</p>
</form>
</div>
<script src = "./js/login.js"></script>
</body>
</html>
Проблема в том, что вы сохраняете всю переменную jcontent
.
Возможно, вы думали, что jcontent.find()
уничтожит другие объекты, но это не так.
Для этого есть разные подходы, но вы можете сделать это
// Store what you found in a variable
const user = jcontent.users.find(r => r.username == uName && r.password == pWord)
// Checks if the user variable is empty or not
if (user) {
// Stringify if there is one.
document.cookie = JSON.stringify(user);
alert("Successfully login!")
} else {
e.preventDefault()
alert("Username or Password is wrong!");
}
Ааа, понятно... когда пользователю удается найти объект, он может конвертироваться с помощью
JSON.stringify
. Я думаю, что я должен сначала вставить переменную «jcontent», чтобы объявить объект JSON. Спасибо за помощь, теперь понял :)