使用JavaScript在网站上显示Cookie [英] Displaying cookies on a website using JavaScript

查看:171
本文介绍了使用JavaScript在网站上显示Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have an assignment I've been working on for 6 hours. I'm supposed to use JavaScript to create a cookie and display the cookie information on the user profile page of a website.

在尝试这个时候,我写了一堆代码,理想情况下,我想使用表单上的提交按钮,最初将信息保存为cookie,然后在查看器返回到网页时显示相同的信息。没有重复我只是把信息放在饼干。所以只要它工作,我不在乎它的工作原理,提交或与我插入的信息。

In attempting this I've written a bunch of code, and ideally I was wanting to use the submit button on the form to initially save the information as a cookie, and then display the same information when the viewer returned to the web page. Failing that repeatedly I've just put information in the cookies. So as long as it works, I don't care how it works, on submit, or with the information I plugged in.

这里是JavaScript:

So here's the 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>

这些信息放在标签中。网站正文如下所示:

This information was placed in the tags. The body of the website looks like this:

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

我不知道如果我放错了东西,或者如果我错过了一些愚蠢,但我看过很多地方,我可以找到。

I don't know if I'm placing something wrong or if I've missed something stupid, but I've looked in as many places as I could find. If someone could please help see what ever I've missed I'd really appreciate it, thank you.

推荐答案

我看到三个主要问题:

1) - 您没有任何代码将当前输入的值保存为新的Cookie值。您需要将保存信息按钮更改为不是提交按钮(您不希望它将表单提交到服务器),而是为您编写的一个新函数,将保存每个表单值到

1) - You don't have any code to save the currently entered values as new cookie values. You need to change the "Save Information" button to not be a submit button (you don't want it submitting a form to the server) and instead hook up a new function to it that you write that will save each form value to the appropriate cookie.

2)在页面初始化时,您正在设置每个cookie,因此任何以前保存的值永远不能使用,因为每次加载页面时总是覆盖它们。

2) Upon page initialization, you are setting every cookie so any previously saved values can never be used because you always overwrite them every time the page is loaded. You should only save initial cookie values if there are no values already saved.

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

3) In the getCookie() function, you declare the argument as cookieFirstName, but then appear to be using cookieName in the function:

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;
}

FYI,我能够通过将您的代码粘贴到 http://jshint.com/ ,并查看其报告。

FYI, I was able to see this error by pasting your code into http://jshint.com/ and looking at its report.

虽然个人,我使用这些测试良好的cookie函数:

Though personally, I use these well tested cookie functions:

// 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()

Also, escape() and unescape() have been deprecated and should not be used. You can use encodeURIComponent() and decodeURIComponent() instead.

这篇关于使用JavaScript在网站上显示Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆