2014-10-20 32 views
0

我已經搜索了幾個地方,試圖找出如何做只顯示一個cookie的價值,而不是整個關鍵,但他們似乎都不必要地複雜,我所做的。我只有一個cookie,只有一個鍵,userName = something,我不知道如何只顯示「something」而不是userName = something。Javascript - 如何僅顯示cookie的值?

function userCookie(form) 
{ 
    if(form.User_Name.value == "") 
    { 
     alert("Cannot accept a blank user name, please enter a valid name"); 
     return false; 
    } 
    else 
    { 
     document.cookie="userName=" + form.User_Name.value; 
     alert(document.cookie); 
     return false; 
    }      
} 

function newWindow() 
{  
    var userWindow = window.open("","MyUserName","height=300,width=300"); 
    userWindow.document.open(); 
    userWindow.document.write("<p>Welcome Back</p>"); 
    userWindow.document.write(document.cookie); 
    userWindow.document.close(); 
} 

回答

0

如果你總是只有一個cookie,那麼document.cookie.split("=")[1]就足夠簡單了。

+0

的實際工作,但它是奇數值後加的東西。我的新窗口顯示「Welcome Back John; RedirectCookie」。任何想法爲什麼RedirectCookie的東西顯示出來? – user3594691 2014-10-20 03:40:57

+0

這是因爲你有多個cookie。 – ghost 2014-10-20 03:44:25

+0

啊,謝謝。我清除了我的cookies,現在它似乎每次都在工作。 – user3594691 2014-10-20 03:49:43

0

document.cookie將始終返回鍵值對,如cookie1=value1;cookie2=value2。 您可以使用以下函數從document.cookie中分割cookieName和「=」以獲取值。

function getCookie(cname) { 
    var name = cname + "="; 
    var ca = document.cookie.split(';'); 
    for(var i=0; i<ca.length; i++) { 
     var c = ca[i]; 
     while (c.charAt(0)==' ') c = c.substring(1); 
     if (c.indexOf(name) != -1) return c.substring(name.length,c.length); 
    } 
    return ""; 
} 

該代碼是從w3schools

0
var cookieArray = document.cookie.split("; "), 
    cookieObject = {}, 
    i, pair; 

for (i = cookieArray.length - 1; i >= 0; i--) { 
    pair = cookieArray[i].split("="); 
    cookieObject[pair[0]] = pair[1]; 
} 

alert(cookieObject.userName); 
0
function getCookie(name) { 
    let x = document.cookie.split(";").find(a => a.includes(name + "=")); 
    return !!x ? x.trim().substr(name.length+1) : "" 
}