使用JavaScript在网站上显示cookie

时间:2015-01-20 06:21:00

标签: javascript html cookies

所以我有一项工作,我已经工作了6个小时。我应该使用JavaScript来创建cookie并在网站的用户个人资料页面上显示cookie信息。

在尝试这个时我写了一堆代码,理想情况下我想使用表单上的提交按钮最初将信息保存为cookie,然后在查看器返回到Web时显示相同的信息页。如果反复失败,我只是将信息放入cookie中。所以只要它有效,我就不在乎它是如何工作的,在提交时,或者是我插入的信息。

所以这是JavaScript:

<script type="text/javascript" language="javascript">
function setCookie(cookieName, cookieValue, cookiePath, cookieExpires){
    cookieValue = escape(cookieValue);
    if (cookieExpires == ""){
    var nowDate = new Date();
    nowDate.setMonth(nowDate.getMonth() + 6);
    cookieExpires = nowDate.toGMTString();
}
if (cookiePath != ""){
    cookiePath = ";Path=" + cookiePath;
}
document.cookie = cookieName + "=" + cookieValue + ";expires=" + cookieExpires + cookiePath;
}

setCookie("cookieFirstName", "George", "", "");
setCookie("cookieLastName", "MaGoo", "", "");
setCookie("cookieEmail", "gMaGoo@gmail.com", "", "");
setCookie("cookieTelNumber", "4095555545", "", "");
setCookie("cookieBirthdate", "12/19/2004", "", "");
setCookie("cookieCity", "Westend", "", "");
setCookie("cookieState", "California", "", "");

function getCookie(cookieFirstName){
var cookieValue = document.cookie;
var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
if (cookieStartsAt == -1){
    cookieStartsAt = cookieValue.indexOf(cookieName + "=");
}
if (cookieStartsAt == -1){
    cookieValue = null;
} else {
    cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
    var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
    if (cookieEndsAt == -1){
        cookieEndsAt = cookieValue.length;
    }
    cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
}
return cookieValue;
}
function yummyCookie(){
  var cFirst = getCookie("cookieFirstName");
  if (cFirst != null){
      document.getElementById("firstname").value = cFirst;
  }
  var cLast = getCookie("cookieLastName");
  if (cLast != null){
      document.getElementById("lastname").value = cLast;
  }
  var cEmail = getCookie("cookieEmail");
  if (cEmail != null){
      document.getElementById("email").value = cEmail;
  }
  var cTelNumber = getCookie("cookieTelNumber");
  if (cTelNumber != null){
      document.getElementById("telnumber").value = cTelNumber;
  }
  var cBirthdate = getCookie("cookieBirthdate");
  if (cBirthdate != null){
      document.getElementById("birthdate").value = cBirthdate;
  }
  var cCity = getCookie("cookieCity");
  if (cCity != null){
      document.getElementById("city").value = cCity;
  }
  var cState = getCookie("cookieState");
  if (cState != null){
      document.getElementById("state").value = cState;
  }
}
</script>

此信息已放入标签中。网站的正文如下:

<body onLoad="yummyCookie()">
<div class="wrapper">


<header class="center" id="banner">
    <h1>Lindsey's Pet Picture Paradise</h1>
  </header>
  <aside id="menu" class="floatleft">
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="businessprofile.html">Business Profile</a></li>
        <li><a href="userprofile.html">User Profile</a></li>
      </ul>
    </nav>
  </aside>
  <div id="content" class="center">
  <h1 id="pageheader">User Profile</h1>
  <form id="userprofile">
  <table>
  <tr>
  <td><label for="firstname">First Name: </label></td>
  <td><input type="text" id="firstname"></td>
  </tr>
  <tr>
  <td><label for="lastname">Last Name: </label></td>
  <td><input type="text" id="lastname"></td>
  </tr>
  <tr>
  <td><label for="email">Email: </label></td>
  <td><input type="email" id="email"></td>
  </tr>
  <tr>
  <td><label for="telnumber">Telephone Number: </label></td>
  <td><input type="tel" id="telnumber"></td>
  </tr>
  <tr>
  <td><label for="birthdate">Birthdate: </label></td>
  <td><input type="date" id="birthdate"></td>
  </tr>
  <tr>
  <td><label for="city">City: </label></td>
  <td><input type="text" id="city"></td>
  </tr>
  <tr>
  <td><label for="state">State: </label></td>
  <td><select id="state">
    <option value="al">AL</option>
    <option value="ak">AK</option>
    <option value="az">AZ</option>
    <option value="ar">AR</option>
    <option value="ca">CA</option>
    <option value="co">CO</option>
    <option value="ct">CT</option>
    <option value="de">DE</option>
    <option value="fl">FL</option>
    <option value="ga">GA</option>
    <option value="hi">HI</option>
    <option value="id">ID</option>
    <option value="il">IL</option>
    <option value="in">IN</option>
    <option value="ia">IA</option>
    <option value="ks">KS</option>
    <option value="ky">KY</option>
    <option value="la">LA</option>
    <option value="me">ME</option>
    <option value="md">MD</option>
    <option value="ma">MA</option>
    <option value="mi">MI</option>
    <option value="mn">MN</option>
    <option value="ms">MS</option>
    <option value="mo">MO</option>
    <option value="mt">MT</option>
    <option value="ne">NE</option>
    <option value="nv">NV</option>
    <option value="nh">NH</option>
    <option value="nj">NJ</option>
    <option value="nm">NM</option>
    <option value="ny">NY</option>
    <option value="nc">NC</option>
    <option value="nd">ND</option>
    <option value="oh">OH</option>
    <option value="ok">OK</option>
    <option value="or">OR</option>
    <option value="pa">PA</option>
    <option value="ri">RI</option>
    <option value="sc">SC</option>
    <option value="sd">SD</option>
    <option value="tn">TN</option>
    <option value="tx">TX</option>
    <option value="ut">UT</option>
    <option value="vt">VT</option>
    <option value="va">VA</option>
    <option value="wa">WA</option>
    <option value="wv">WV</option>
    <option value="wi">WI</option>
    <option value="wy">WY</option>
  </select></td>
  </tr>
  <tr>
  <td colspan="2"><input type="submit" value="Save Your Information!"></td>
  </tr>
  </table>
  </div>
  <footer>Safe and friendly place to share your love of your pets with others! Design by Lindsey Schreiner.<br /> Forget your user name or password? <a href="##">Click here for help</a>.</footer>
</div>
</body>

我不知道我是否犯了错误或者我错过了一些愚蠢的东西,但我已经找到了尽可能多的地方。如果有人能帮忙看看我错过了什么,我真的很感激,谢谢。

1 个答案:

答案 0 :(得分:1)

我看到三个主要问题:

1) - 您没有任何代码可以将当前输入的值保存为新的cookie值。您需要将“保存信息”按钮更改为不是提交按钮(您不希望它将表单提交到服务器),而是将您编写的新功能挂钩到该保存按钮,将每个表单值保存到适当的cookie。

2)在页面初始化时,您正在设置每个cookie,因此永远不会使用任何以前保存的值,因为每次加载页面时都会覆盖它们。如果没有已保存的值,则只应保存初始cookie值。

3)在getCookie()函数中,您将参数声明为cookieFirstName,但似乎在函数中使用cookieName

function getCookie(cookieFirstName) {
    var cookieValue = document.cookie;
    var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
    if (cookieStartsAt == -1) {
        cookieStartsAt = cookieValue.indexOf(cookieName + "=");
    }
    if (cookieStartsAt == -1) {
        cookieValue = null;
    } else {
        cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
        var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
        if (cookieEndsAt == -1) {
            cookieEndsAt = cookieValue.length;
        }
        cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
    }
    return cookieValue;
}

据推测,它应该是这样的:

function getCookie(cookieName) {
    var cookieValue = document.cookie;
    var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
    if (cookieStartsAt == -1) {
        cookieStartsAt = cookieValue.indexOf(cookieName + "=");
    }
    if (cookieStartsAt == -1) {
        cookieValue = null;
    } else {
        cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
        var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
        if (cookieEndsAt == -1) {
            cookieEndsAt = cookieValue.length;
        }
        cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
    }
    return cookieValue;
}

仅供参考,我可以通过将您的代码粘贴到http://jshint.com/并查看其报告来查看此错误。


虽然我个人使用这些经过良好测试的cookie功能:

// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/" 
//   and can limit which pages on your site can 
//   read the cookie.
//   By default, all pages on the site can read
//   the cookie if path is not specified
function createCookie(name, value, days, path) {
    var date, expires = "";
    path = path || "/";
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=" + path;
}

function readCookie(name) {
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

此外,escape()unescape()已被弃用,不应使用。您可以改为使用encodeURIComponent()decodeURIComponent()