我在一个页面上存储了一个cookie,并在表单中使用此函数进行输入:
<script type="text/javascript">
function WriteCookie()
{
emailValue = escape(document.form.01_email.value) + ";";
userIDValue = escape(document.form.01_userID.value) + ";";
document.cookie="email=" + emailValue;
document.cookie="userID=" + userIDValue;
}
</script>
<form name="form">
<input type="email" class="form-textbox validate[required, Email]" id="input_10" name="01_email" size="26" value="email@email.com" />
<input type="hidden" id="simple_spc" name="01_userId" value="1234" />
</form>一旦用户提交表单,我将被重定向到另一个页面,并且我使用以下代码检索cookie,但我需要让它找到cookie中的电子邮件和userID,并将其插入到这个新页面的输入值中:
<script type="text/javascript">
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[1];
value = cookiearray[i].split('=')[2];
alert("Email is : " + name + " and UserID is : " + value);
}
}
</script>
<form name="form">
<input type="email" class="form-textbox" id="input_10" name="02_email" size="26" value="" />
<input type="hidden" id="simple_spc" name="02_userId" value="" />
</form>我知道用户很可能有多个cookies,所以只查找我遇到问题的电子邮件和userID。
发布于 2012-04-26 01:49:13
试试这个来读你的cookies吧。
function ReadCookie(){
var key, value, i;
var cookieArray = document.cookie.split(';');
for (i = 0; i < cookieArray.length; i++){
key = cookieArray[i].substr(0, cookieArray[i].indexOf("="));
value = cookieArray[i].substr(cookieArray[i].indexOf("=")+1);
if (key == 'email'){
alert('Email is ' + value);
}
if (key == 'userID'){
alert('userID is ' + value);
}
}
}发布于 2012-04-26 01:43:51
试试这个:
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[1];
value = cookiearray[i].split('=')[2];
if (name == "email")
alert("Email is : " + value);
if (name == "userID")
alert("UserID is : " + value);
}发布于 2012-04-26 02:08:08
我不会把这个答案归功于它,但没有人能比quirksmode.org的PPK更优雅了,它的解决方案中包含了“为什么它有效”的问题。
代码如下:
function createCookie(name,value,days) {
if (days) {
var date = new Date(),
expires = "";
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
} else {
document.cookie = name+"=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=",
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);
}这是PPK on Cookies
HTH
https://stackoverflow.com/questions/10320827
复制相似问题