简体   繁体   中英

How to Store data json into cookies in javascript

I need help from you. Can you guide me, please?
I use JSON as data accounts. But, I need to create a session with a cookie.

The case is when I successfully logged in, the cookie was created, but only a user that I logged in was created. Not all of the objects in data JSON.

The JSON file is:

{ "users": [{
        "id": 1,
        "first_name": "John",
        "last_name": "Doe",
        "email": "johndoe@gmail.com",
        "username": "john20",
        "password": "doe20"
    },
    {
        "id": 2,
        "first_name": "Julia",
        "last_name": "Chan",
        "email": "juliachan@gmail.com",
        "username": "julia19",
        "password": "chan19"
    }
    ]
}

So when I logged in with the username julia19 with a true password, I will be logged in and the cookie was created with full information about username julia19 (id, first_name, last_name, email, username, password).

I using

document.cookie = JSON.stringify(jcontent);

but it shows all of the objects in the JSON file.

The full file is:

 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>

The problem is you're storing the whole jcontent variable. Maybe, you thought jcontent.find() will eliminate the other objects, but it doesn't.

There are different approaches for this but you can do this

// 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!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM