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

sycxhyv7  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(104)

我试图存储密码和用户名内的cookie和当用户再次登录到该页面应该显示用户名和密码这里是cookie的功能,它应该存储的cookie为15天,然后它到期
这里是代码

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

这里是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();}

但是当我刷新页面时,输入字段中的文本消失了

f87krz0w

f87krz0w1#

试试这个

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">
r7knjye2

r7knjye22#

我不知道,这些都说不通!我试图创建一个网站,失败得很惨。我的名字是Rediet顺便说一很高兴认识你!

相关问题