【问题标题】:trying to store username and password in cookie with JavaScript尝试使用 JavaScript 将用户名和密码存储在 cookie 中
【发布时间】:2020-05-12 02:16:40
【问题描述】:

我正在尝试将密码和用户名存储在 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();} 

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

【问题讨论】:

  • 您不应该永远将密码以明文形式存储在 cookie 中。
  • 什么是pwds?是密码,还是密码输入元素。
  • @WiktorZychla - 除非是作业明确要求这样做。
  • @PM77-1 如果任何班级有那个作为作业,我会要求系主任调查教授向学生群体灌输可怕的想法。
  • 我们需要更多信息来诊断问题。此处提供的代码中没有任何内容会在刷新后显示用户名或密码。

标签: javascript html cookies


【解决方案1】:

试试这个

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

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 2012-01-20
    • 2011-08-19
    • 2013-12-27
    • 2014-01-01
    • 2019-09-02
    • 2010-12-27
    • 2014-11-30
    • 1970-01-01
    相关资源
    最近更新 更多