我正在一个页面上存储一个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中找到电子邮件和用户ID并将其插入到此新输入的值中页:
<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>
我知道用户很可能会有多个Cookie,因此只查找我遇到问题的电子邮件和用户ID。
答案 0 :(得分:0)
试试这个:
// 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);
}
答案 1 :(得分:0)
尝试此操作来阅读您的Cookie。
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);
}
}
}
答案 2 :(得分:0)
我不会因为这个答案而受到赞扬,但是在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);
}
HTH