问题消息cookie

时间:2013-11-16 12:44:13

标签: javascript

我需要维护用户输入的文本(通过表单)30天,并且该文本在网站的每个页面上都可见。我以为我会用饼干处理它,但我没有成功。

HTML

<body onload="verificaCookie()">
<a href="javascript:window.alert(document.cookie.split(';').join(''))">Tutti i cookies</a>
<div id="div_form">
    <form id="myform" method="post" action="#" onsubmit="send()">
            <input id="myinput" type="text" name="myinput" size="20" maxlength="30" value="Messaggio..."/>              
            <input type="button" value="Send" onclick="send()"/>
        </div>
        <div id="msg"><p id="mgs_view"></p></div>
    </form>
</div>

JAVASCRIPT

if(!navigator.cookieEnabled) {
    alert("Non hai i cookie abilitati.");
}
function scriviCookie(nomeCookie,valoreCookie,durataCookie){
    var scadenza = new Date();
    var adesso = new Date();
    scadenza.setTime(adesso.getTime() + (parseInt(durataCookie) * 60000));
    document.cookie = nomeCookie + '=' + escape(valoreCookie) + '; expires=' + scadenza.toGMTString() + '; path=/';
}
function leggiCookie(nomeCookie){
if (document.cookie.length > 0){
  var inizio = document.cookie.indexOf(nomeCookie + "=");
  if (inizio != -1){
    inizio = inizio + nomeCookie.length + 1;
    var fine = document.cookie.indexOf(";",inizio);
    if (fine == -1) fine = document.cookie.length;
    return unescape(document.cookie.substring(inizio,fine));
  }
  else{
     return "";
  }
}
return "";

}

function verificaCookie(){
    var res = leggiCookie("testo");
    if(res != ""){
        document.getElementById("div_form").innerHTML = res + "";
    }
}

function send() {
    var testo = document.getElementById("myinput").value;   
    scriviCookie("testo", testo, 30);
    document.getElementById("mgs_view").innerHTML = testo;
}

这样做不起作用,但cookie已启用。 Chrome不会这样做,而Firefox知道cookie会保存我但不会显示文本..

我为我可怜的英语道歉。

1 个答案:

答案 0 :(得分:0)

您可能想尝试查看localstorage http://diveintohtml5.info/storage.html

请注意,moderm浏览器支持此功能,因此如果向后兼容性不是问题,那么您可以使用它。