【问题标题】:Reading Cookie that was saved using javascript into html将使用 javascript 保存的 Cookie 读入 html
【发布时间】:2015-12-29 14:29:41
【问题描述】:

我一直在尝试将使用 javascript 保存的 Cookie 显示到 html 页面中 我将我的 Javascript 保存在外部文件中,我不打算将其放在服务器上,这仅用于教育客户目的

我使用此代码存储我的 cookie Javascript 文件:`

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    var pass=getCookie("password");
    if (user != "" || pass != "") {
        alert("Welcome again " + user + " your password is: " + pass);
    } else {
       user = prompt("Welcome to my Site! Enter your name to begin! :","");
       pass = prompt("Make sure to include a password might be useful later! :","");
       if ((user != "" && user != null)&&(pass != "" && pass != null)) {
           setCookie("username", user, 30);
           setCookie("password", pass, 30);
       }               
    }   
}

` 和 HTML

<body onload="checkCookie()">

从我收集的信息来看,这似乎工作正常,因为弹出对话框是这样说的 我想要做的是把这个用警告框保存的 cookie 显示在 html 端,所以它看起来像这样

<p>Your cookie is ("Displays the cookie here")</p>

到目前为止,我尝试做的是:

<script type="text/javascript">      
  document.write(getCookie("username"));
</script>

如果有人能指出我正确的方向或说出我做错了什么,我将不胜感激

【问题讨论】:

    标签: javascript html cookies


    【解决方案1】:

    添加&lt;div id='cookieInfo'&gt;&lt;/div&gt;的HTML元素

    将您的 Javascript 更改为:

    document.getElementById('cookieInfo').innerHTML = getCookie('userrname');
    

    【讨论】:

      【解决方案2】:

      试试这个fiddle

      这是javascript

      $('document').ready(function(){
          checkCookie();
        document.getElementById("myc").innerHTML = getCookie("username");
      })
      

      这是你的html

      <p>Your name is <span id="myc"></span></p>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-25
        • 2011-08-25
        • 1970-01-01
        • 1970-01-01
        • 2011-03-30
        • 2019-02-11
        • 2011-02-23
        • 1970-01-01
        相关资源
        最近更新 更多