如何獲取cookie值

前端嵐楓發表於2012-09-10


獲取cookie的值
在上一節談到了讀取cookie的名與值,可以看到,只能夠一次獲取所有的cookie值,而不能指定cookie名稱來獲得指定的值,這樣就必須從cookie中找到你要那個值,因此處理起來可能有點麻煩,使用者必須自己分析這個字串,所以得用到幾個常見的字元處理函式來獲取指定的cookie值。
具體的實現方法如下所示。


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文件</title>
<script language="JavaScript" type="text/javascript">
<!--
    document.cookie="id=828";                //設定一個名為usr值為828的cookie值
    document.cookie="usr=yx";                //設定一個名為usr值為yx的值
    var str=document.cookie;                //獲取cookie字串    
    var arr=str.split("; ");                //將多cookie切割為多個名/值對
    var userIndex="";                        //定義一個空字串
    var i=0;                                //定義一個變數並賦值0
    while(i<arr.length)                    //遍歷cookie陣列,處理每個cookie對            
        {
            var arrs=arr[i].split("=");    //用“=”將cookie的名與值分開
            if("id"==arrs[0])                //找到名稱為user的cookie,並返回它的值
            {
                userIndex=arrs[1];            //將獲取的值儲存在變數userIndex中
                break;                        //結束迴圈
            }
            i++;                            //變數i加1
        }
    if(userIndex!="")                        //判斷所要查詢的值是否存在
        alert(userIndex);                    //輸出userIndex的值
    else
        alert("查無此值")                    //沒有查到要查的值
//-->
</script>


</head>

<body>
</body>
</html>


相關文章