2017-03-16 138 views
0

我想將來自HTML輸入標記的用戶輸入作爲cookie存儲,以便稍後使用。我需要讀取多個輸入框,並在用戶點擊按鈕時存儲文本值。JavaScript:設置Cookie不起作用

我的問題是,保存信息到一個cookie似乎不正確工作,而不是保存任何信息,從我可以使用警報(document.cookie中)

HTML代碼中看到:

<form id="contact-form"> 
    <label for="name">Log entry name:</label> 
    <input type="text" id = "eName" value="" placeholder="Run at the park"/> 
    <label for="email">Name of exercise:</label> 
    <input type="name" id = "exercise" value="" placeholder="Jogging" /> 
    <label for="telephone">Date: </label> 
    <input type="number" id = "date" value="" /> 
    </form> 

<li><a href="#" onclick ="setCookie()"> Add New Log</a></li> 
<li><a href="#" onclick ="getCookie()"> cookie</a></li> 

的JavaScript:

<script type = "text/JavaScript"> 
function setCookie(){ 

var cookieString = "entry=" + document.getElementById("eName").value + 
        ";exercise=" + document.getElementById("exercise").value + 
        ";date=" + document.getElementById("date").value ; 

document.cookie = cookieString; 

} 

function getCookie(){ 

alert(document.cookie); 

} 

當我告訴餅乾作爲警告,這是響應:

enter image description here JavaScript新手,所以請溫和我謝謝你,所有的幫助appriciated。

回答

2

您無法通過使用document.cookie來讀取cookie。

爲了讀取cookie時,使用此:

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 ""; 
}