以JSON字符串序列化自定义对象,对其进行解析,然后存储在cookie中。
对于每个键/值对,请使用单独的cookie。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Course: <input type="text" id="course"><br>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
//Declaring 3 key-value pairs
var info="Name="+ document.getElementById("name").value+";Email="+document.getElementById("email").value+";Course="+document.getElementById("course").value;
//Providing all 3 key-value pairs to a single cookie
document.cookie=info;
}
function getCookie()
{
if(document.cookie.length!=0)
{
//Invoking key-value pair stored in a cookie
alert(document.cookie);
}
else
{
alert("Cookie not available")
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Course: <input type="text" id="course"><br>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
var obj = {};//Creating custom object
obj.name = document.getElementById("name").value;
obj.email = document.getElementById("email").value;
obj.course = document.getElementById("course").value;
//Converting JavaScript object to JSON string
var jsonString = JSON.stringify(obj);
document.cookie = jsonString;
}
function getCookie()
{
if( document.cookie.length!=0)
{
//Parsing JSON string to JSON object
var obj = JSON.parse(document.cookie);
alert("Name="+obj.name+" "+"Email="+obj.email+" "+"Course="+obj.course);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Course: <input type="text" id="course"><br>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<script>
function setCookie()
{
document.cookie = "name=" + document.getElementById("name").value;
document.cookie = "email=" + document.getElementById("email").value;
document.cookie = "course=" + document.getElementById("course").value;
}
function getCookie()
{
if (document.cookie.length != 0)
{
alert("Name="+document.getElementById("name").value+" Email="+document.getElementById("email").value+" Course="+document.getElementById("course").value);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>