读取使用javascript保存到html中的Cookie

时间:2015-12-29 06:16:50

标签: javascript html cookies

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

我使用此代码 Javascript文件:`

存储我的Cookie
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>

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

2 个答案:

答案 0 :(得分:0)

添加<div id='cookieInfo'></div>

的HTML元素

将您的Javascript更改为:

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

答案 1 :(得分:0)

试试这个fiddle

这是javascript

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

这是你的HTML

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