我正在开发一个在客户端使用cookie的项目。我刚开始创建cookie。我们希望在任何表单上保存用户输入,因此如果用户在另一个页面上访问另一个表单,我们可以使用上一个表单中的输入自动填充该表单。
该网站是用PHP和AngularJS构建的,但我首先处理JavaScript解决方案,因为我正在努力使用AngularJS版本。它在FF和IE中运行良好,但Chrome给了我一个错误 - 未捕获的SyntaxError:意外的令牌u。我已经阅读过有关同一问题的其他StackOverflow文章,但我不明白他们如何说我们可以修复它。
我的JavaScript解决方案源于此:https://www.youtube.com/watch?v=P4Zlc6pdHgM
第一页表单(我称之为key-value-pairs.html):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<table border="1">
<tr>
<td>First Name</td>
<td><input type="text" id="form_000c_fld_0_fn" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" id="form_000c_fld_0_ln" /></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Set Cookie" onClick="doSubmit()" />
<a href="key-value-pairs-2.html">Let's see if this works</a>
</td>
</tr>
</table>
<script type="text/javascript">
function doSubmit(){
var customObject = {};
customObject.name = document.getElementById("form_000c_fld_0_fn").value;
customObject.last = document.getElementById("form_000c_fld_0_ln").value;
var jsonString = JSON.stringify(customObject);
document.cookie = "cookieObject=" + jsonString;
}
function getCookie(){
var nameValueArray = document.cookie.split("=");
var customObject = JSON.parse(nameValueArray[1]);
document.getElementById("first_name").value = customObject.name;
document.getElementById("last_name").value = customObject.last;
}
</script>
</body>
</html>
表单(我称之为key-value-pairs-2.html):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body onLoad="getCookie()">
<table border="1">
<tr>
<td>First Name</td>
<td><input type="text" id="first_name" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" id="last_name" /></td>
</tr>
<tr>
<td colspan="2">
<a href="key-value-pairs.html">Let's test another one</a>
</td>
</tr>
</table>
<script type="text/javascript">
function doSubmit(){
var customObject = {};
customObject.name = document.getElementById("form_000c_fld_0_fn").value;
customObject.last = document.getElementById("form_000c_fld_0_ln").value;
var jsonString = JSON.stringify(customObject);
document.cookie = "cookieObject=" + jsonString;
}
function getCookie(){
var nameValueArray = document.cookie.split("=");
var customObject = JSON.parse(nameValueArray[1]);
document.getElementById("first_name").value = customObject.name;
document.getElementById("last_name").value = customObject.last;
}
</script>
</body>
</html>
答案 0 :(得分:0)
您的代码假定只存在一个cookie。尝试使用这些功能来设置和获取cookie。
function setCookie(name, value) {
var cookie = name + "=" + escape(value) + ";";
document.cookie = cookie;
}
function getCookie(name) {
var chunks = document.cookie.split(";");
for(var i=chunks.length; i--;){
if(chunks[i].trim().split("=")[0].trim() == name){
return chunks[i].trim().split("=")[1].trim();
}
}
return null;
}