此脚本根据表单数据创建cookie(例如:?docname = My Document )
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
}
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function saveDoc() {
if (docname != '') {
setCookie(docname,url,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
它创建cookie并将其名称设置为 docname 变量,但是当它将url设置为值时,它会切断表单数据。
我研究并更改了代码但找不到答案,有人可以帮忙吗?
解决方案
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
var recode = encodeURIComponent(url);
}
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function saveDoc() {
if (docname != '') {
setCookie(docname,recode,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
更改了用于将值设置为recode
的变量,并将recode设置为encodeURIComponent(url);
,因此它对url
进行解码,对其进行解码并使表单数据成为可能或者cookie的名称等。感谢@epascarello
答案 0 :(得分:1)
encodeURIComponent()
是你的朋友
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
当你得到它时,你需要用decodeURIComponent()
解码它。