如何在javascript中读取特定的cookie名称?

时间:2013-07-12 05:07:23

标签: javascript cookies

这是我写cookie的方式。我的问题是如何阅读这个特定的cookie名称。谢谢!

  

HTML CODE:

<form name="myform" action="">  
        <input style="display:none;" type="text" name="indexValue" id="cookie"/>  
        <input style="display:none;" type="text" name="moviePath" id="path"/>  
</form>
JAVASCRIPT CODE:
    function WriteCookie()
    {
        cookievalue= escape(document.myform.indexValue.value) + ";";
        path= escape(document.myform.moviePath.value) + ";";
        document.cookie="name=" + cookievalue;
        document.cookie="path=" + path;
    }

2 个答案:

答案 0 :(得分:0)

如果您想让自己的工作变得非常轻松,请使用预先编写的工具,例如this onethis one。解析cookie可能会变得棘手,最好回到其他人的工作来完成这样的常见任务。

以下是QuirksMode文章的片段:

function readCookie(name) {
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

答案 1 :(得分:0)

function getCookie(cName){
    if(document.cookie&&document.cookie.length){
           cStart = document.cookie.indexOf(cName + "=")
           if(cStart!=-1){
               //the index of value need to add cookie name's length and 1("=".length)
               cStart=cStart + cName.length + 1; 
               cEnd=document.cookie.indexOf(";",cStart);
               if(cEnd==-1){
                   cEnd=document.cookie.length;
               }
               return unescape(document.cookie.substring(cStart,cEnd));
          } 
     }
     return ""
}

基于JavaScript Cookies w3schools.com

的代码