简体   繁体   English

尝试使用 JavaScript 将用户名和密码存储在 cookie 中

[英]trying to store username and password in cookie with JavaScript

I am trying to store the password and username inside a cookie and when the user logs in again to the page it should show the username and password here is the cookie function, it should store the cookie for 15 days and then it expires我正在尝试将密码和用户名存储在 cookie 中,当用户再次登录页面时,它应该显示用户名和密码,这里是 cookie function,它应该存储 cookie 15 天然后过期

here is the code这是代码

                <input type="text" id=user ><br>
                <label for="key" id=passlbl>password:</label><br>
                <input type="password" id="pd">

here is the javascript这是 javascript

let username = document.getElementById("user");
let pwd = document.getElementById("pd");

createCookie(username.value,pwd.value)

function createCookie(name,pwds){
    today = new Date();
    var expire = new Date();
    expire.setTime(today.getTime() + 3600000*24*15);
    document.cookie = name.value+"="+encodeURI(pwds.value)+";path=/" + ";expires="+expire.toUTCString();} 

but when I refresh the page the text inside the input fields disappear但是当我刷新页面时,输入字段中的文本消失了

Try this尝试这个

 function createCookie(name,pwds){ let username = document.getElementById("user"); let pwd = document.getElementById("pd"); today = new Date(); var expire = new Date(); expire.setTime(today.getTime() + 3600000*24*15); document.cookie = "name="+username.value+";path=/" + ";expires="+expire.toUTCString(); document.cookie = "password="+encodeURI(pwd.value)+";path=/" + ";expires="+expire.toUTCString(); //can only write one entity at a time (name, pass) } //event handler for page load - runs on every refresh window.onload = function(){ //how to read back the stored name and password? //https://stackoverflow.com/q/10730362/6160662 //https://stackoverflow.com/q/5639346/6160662 //for now var uname = 'Route66'; var pass = '123456'; document.getElementById('user').value = uname; document.getElementById('pd').value = pass; }
 <input type="text" id="user"> <input type="password" id="pd"> <input type="button" onclick="createCookie()" value="submit">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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