奇怪的cookie错误,javascript

Strange cookie bug, javascript

本文关键字:javascript 错误 cookie      更新时间:2023-09-26

我根本不明白为什么会发生这种情况。我有一个表单和一个按钮,该按钮调用一个方法,该方法使用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.  
}

有人能弄清楚这里发生了什么吗?

试试这个:-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);
}

控制台日志

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]