阅读Cookie会给出奇怪的格式

时间:2012-05-01 11:56:46

标签: javascript cookies

我正在尝试读取名为Pdf的cookie,其值为

http://engine.edocbuilder.com/include/fileDownload-aspx?p=xBfpz3UGPkWamLTDILo%2fWbFqh3FomdYuByiTwfB4RXN0sDN6tY%2fDfxJzzfPZblUl5aSBO3v96%2bJ6acwT7L5oi8tyMuGwKshYtGK%2bfhgiSfM%3d&s=4995b496-e735-4a26-9801-253a34ab0481

但是当我读到这个cookie时,我会得到以下格式的价值,你能告诉我有关它的解决方案吗?     

s=a4823a90%2D80e6%2D4006%2D909c%2D69d567f2d318&http%3A%2F%2Fengine%2Eedocbuilder%2Ecom%2Finclude%2FfileDownload%2Easpx%3Fp=%2BRj53ETGUI%2FeK7H8yo2Zj%2F6z9Ggmk4VEgmPEtoA2NPDhomzjaYvk2wkh0OZzWt8OtDcATY%2BknqGG8AuxddA6LWccWAfbQgtI0dlVkWevheg%3D

以下是读取cookie的代码:

var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
     x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
     y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
     x=x.replace(/^\s+|\s+$/g,"");
     if (x==c_name)
     {
         return unescape(y);
     }
 }

3 个答案:

答案 0 :(得分:1)

读取和写入cookie使用此功能:

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + "; path=/");
}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) 
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

答案 1 :(得分:0)

Cookie包含URL编码数据。使用unescape解码字符串:

var cookie = "s=a4823a90%2D80e6%2D4006%2D909c%2D69d567f2d318&http%3A%2F%2Fengine%2Eedocbuilder%2Ecom%2Finclude%2FfileDownload%2Easpx%3Fp=%2BRj53ETGUI%2FeK7H8yo2Zj%2F6z9Ggmk4VEgmPEtoA2NPDhomzjaYvk2wkh0OZzWt8OtDcATY%2BknqGG8AuxddA6LWccWAfbQgtI0dlVkWevheg%3D"
// Find starting position of "http" and retrieve the URL from there
var unEscapedURL = unescape(cookie.substring(cookie.indexOf("http"), cookie.length));

这是a working fiddle

答案 2 :(得分:0)

只需使用原生decodeURIComponent方法即可获得正确的格式:

return decodeURIComponent(y);

Live test case

“问题”在编写cookie的代码中,由于某种原因编写了编码。