2016-10-13 3 views
0

JavaScriptでセッションとCookieを学習しています。私はいくつかのデータを取り、次のように別のページ(2ページ目)に表示されるセッションとクッキー変数に格納し、フォームがあります。JavascriptのセッションとCookieが保存されていない(動作していない)

<html> 
<body> 
<form action="second.html" onsubmit="return myFunction();"> 
Enter a session variable: <input id="sess" type="text" /> 
</br> 
Enter a coockie variable: <input id="cookiess" type="text" /> 

</br> 
<input type="submit" /> 
</form> 

<script> 
function myFunction() { 
document.cookie = "username="+document.getElementById("cookiess").value + "; expires=Fri, 14 Oct 2016 12:00:00 UTC"; 
sessionStorage["myKey"] = document.getElementById("sess").value; 

return true; 
} 

</script> 
</body> 
</html> 

を、これはsecond.htmlページです:

<html> 
<body> 

<script> 

alert(sessionStorage["myKey"] + document.cookie); 
</script> 
</body> 
</html> 

しかし、警告関数にセッション変数とCookie変数を表示すると、空の変数が表示されます。セッション変数とCookie変数が機能しない理由

+1

Webサーバー上の両方のファイルをホストするか、あなたが二番目をリフレッシュしますが動作しません。 ? –

+0

いいえ、あなたはその理由を意味しますか? –

+2

'file://'プロトコルからこれを実行しているだけなら、それは動作しません。 – adeneo

答えて

2

こんにちは、セッションの保存方法を確認する場合は、以下のコードを参照してください... その1ページです。

あなただけのファイルからこれを実行している場合は2ページがある場合://プロトコル、それは

<!DOCTYPE html> 
<html> 
<head> 
<script> 
function clickCounter() { 
    if(typeof(Storage) !== "undefined") { 
     if (sessionStorage.clickcount) { 
      sessionStorage.clickcount = Number(sessionStorage.clickcount)+1; 
      sessionStorage["myKey"] = sessionStorage.clickcount; 
     } else { 
      sessionStorage.clickcount = 1; 
     } 
     document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session."+sessionStorage["myKey"]; 
    } else { 
     document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage..."; 
    } 
} 
</script> 
</head> 
<body> 
<p><button onclick="clickCounter()" type="button">Click me!</button></p> 
<div id="result"></div> 
<p>Click the button to see the counter increase.</p> 
<p>Close the browser tab (or window), and try again, and the counter is reset.</p> 
</body> 
</html> 
関連する問題