JavaScript:设置 cookie 不起作用

标签 javascript html cookies

我想将 HTML 输入标记中的用户输入存储为 cookie 以供稍后使用。当用户单击按钮时,我需要读取多个输入框并存储文本值。

我的问题是,从我使用alert(document.cookie)看到的情况来看,将信息保存到cookie似乎无法正常工作,而是没有保存任何信息

HTML 代码:

<form id="contact-form">
    <label for="name">Log entry name:</label>
    <input type="text" id = "eName"  value="" placeholder="Run at the park"/>
    <label for="email">Name of exercise:</label>
    <input type="name" id = "exercise"  value="" placeholder="Jogging"  />
    <label for="telephone">Date: </label>
    <input type="number" id = "date" value="" />
    </form>

<li><a href="#" onclick ="setCookie()"> Add New Log</a></li>
<li><a href="#" onclick ="getCookie()"> cookie</a></li>

JavaScript:

<script type = "text/JavaScript">
function setCookie(){

var cookieString = "entry=" + document.getElementById("eName").value +
                    ";exercise=" + document.getElementById("exercise").value +
                    ";date=" + document.getElementById("date").value ;

document.cookie = cookieString;

}

function getCookie(){

alert(document.cookie);

}

当我将 cookie 显示为警报时,这是响应:

enter image description here javascript 新手,所以请对我温柔点,谢谢,所有帮助都会得到帮助。

最佳答案

您无法使用 document.cookie 读取 cookie。

要读取 cookie,请使用:

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

关于JavaScript:设置 cookie 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840311/

相关文章:

javascript - 更改输入背景而不更改默认边框

javascript - 从1数到24然后重新开始

java - 一个浏览器中存在两个基于 servlet 引擎 cookie 的 session 的问题

java - 使用 crawler4j 发送请求中的 cookie?

php - 访问 magento 管理面板时连接被重置

javascript - HTML 注释标签中的 Javascript 是否仍应为 "hidden"?

javascript - ES6 为什么在循环中定义时可以重新分配常量

javascript - 在react js中访问json文件

html - Rails,如何在选中时提交带有 true 的禁用复选框

javascript - 是否可以将 <md-select> 与 <md-icon> 集成?