在这个例子中,我要通过提示询问用户他们的名字,然后使用cookie写入div,“Welcome,savedCookie!”进入之后,然后每次他们在到期前访问页面。
我让浏览器提示询问我的名字,然后它将div写为“欢迎,未定义!”我无法弄清楚为什么会收到错误。
//Setting cookie for Users Name
function set_it() {
var userName = prompt("Please Enter Your Name", ""),
thetext = "name=" + userName,
expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC",
newtext = encodeURIComponent(thetext);
newtext += expdate;
document.cookie = newtext;
}
//Reading & Writing cookie
function read_it() {
var rawCookie = document.cookie;
bakedCookie = decodeURIComponent(rawCookie);
yumCookie = bakedCookie.split("=");
document.getElementById("greeting").innerHTML = "<p>Welcome, " + yumCookie[1] + "!</p>";
}
if (document.cookie) {
read_it();
} else {
set_it();
read_it();
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="greeting">
<script src="prjs13_2.js"></script>
</div>
</body>
</html>
答案 0 :(得分:0)
尝试在控制台中运行您的唯一代码,看看你得到了什么 -
var userLocation;
function getUserLocation() {
$.ajax({
url: 'https://www.example.com/location.json',
success: function(response) {
userLocation = response.coordinates;
}
}).done(function() {
getCurrentWeather()
});
}
function getCurrentWeather() {
$.ajax({
url: 'https://www.example.com/weather' + userLocation + '.json',
success: function(response) {
console.log(response);
}
});
}
我是为了这个名字&#34; david&#34;我得到了这个 -
name%3Ddavid; expires = Mon,2017年3月27日13:00:00 UTC&#34;
当您设置Cookie时,您的name属性无效。 请尝试使用此代码(不使用encodeURIComponent和;而不是逗号) -
var userName = prompt("Please Enter Your Name", ""),
thetext = "name=" + userName,
expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC",
newtext = encodeURIComponent(thetext);
newtext += expdate;
document.cookie = newtext;
答案 1 :(得分:0)
您可以使用以下功能来获取/设置Cookie:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
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");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
以下是一些小提琴示例:fiddle