奇怪的cookie bug,javascript

时间:2013-11-21 03:49:15

标签: javascript jquery cookies

我无法弄清楚为什么会发生这种情况。我有一个表单和一个调用方法的按钮,该方法使用jQuery序列化表单并将其粘贴到cookie中,这里:

function serializeFormToCookie(){
var str = $("form").serialize();
alert(str);

document.cookie = str + "&expires=" + expires.toUTCString()

alert("You have successfully stored your reservation, please click show if you would like to review it.")
}

(当我快速检查并提醒(str)时,字符串完全符合我的预期。

这里有第二个调用show方法的按钮是show方法:

function showData(){
var savedCookie = document.cookie
var dataArray = savedCookie.split("&")
alert(dataArray[0]) //this is blank! it should be the first key value pair from str!
alert(dataArray[1]) //this is "; key=value" I have NO idea where the ";" is coming from!
alert(datArray[2....etc]) //this is perfect, comes up as key=value.  
}

有人能弄明白这里发生了什么吗?

1 个答案:

答案 0 :(得分:0)

试试这个: - http://jsfiddle.net/c2znX/

<强> HTML: -

<form>
    <input type="text" name="firstname" />
    <input type="text" name="lastname"/>
    <input type="text" name="email" />
</form>

<input type="button" onclick="serializeFormToCookie()"  value="Store" />
<input type="button" onclick="showData()"  value="Show" />

<强> JS: -

function serializeFormToCookie() {
    var str = $("form").serialize();
    alert(str);

    var expires = new Date("October 13, 2015 11:13:00");

    document.cookie = str + "&expires=" + expires.toUTCString();

    alert("You have successfully stored your reservation, please click show if you would like to review it.");
}

function showData() {
    var savedCookie = document.cookie;
    var dataArray = savedCookie.split("&");
    console.log(document.cookie);
    console.log(dataArray);
}

<强> CONSOLE.LOG

Array[5]
0: "firstname=john"
1: "lastname=phillips"
2: "email=john%40philips.com"
3: "expires=Tue, 13 Oct 2015 05:43:00 GMT; csrftoken=4mJGsAuQ3DtgZ5HNLZJNBPkOwAqCH5zo; __utma=45159731.617712919.1381735611.1383277585.1384938305.3; __utmc=45159731; __utmz=45159731.1381735611.1.1.utmcsr=jsfiddle.net|utmccn=(referral)|utmcmd=referral|utmcct=/S9Hgg/5/; PRUM_EPISODES=s=1384938369829"
4: "r=http%3A//fiddle.jshell.net/_display/test1.html; BCSI-CS-560d5cf3f6036b02=2"
length: 5
__proto__: Array[0]