我编写了一个创建 cookie 的脚本,并根据表单数据设置名称和值?docname=,
getValue来自获取表单数据的此脚本:
<script type="text/javascript">
<!-- hide from old browsers
function getValue(varname)
{
// First, we load the URL into a variable
var url = window.location.href.replace(new RegExp( "\\+", "g" ), "%20" )
// Next, split the url by the ?
var qparts = url.split("?");
// Check that there is a querystring, return "" if not
if (qparts.length == 0)
{
return "";
}
// Then find the querystring, everything after the ?
var query = qparts[1];
// Split the query string into variables (separates by &s)
var vars = query.split("&");
// Initialize the value with "" as default
var value = "";
// Iterate through vars, checking each one for varname
for (i=0;i<vars.length;i++)
{
// Split the variable by =, which splits name and value
var parts = vars[i].split("=");
// Check if the correct variable
if (parts[0] == varname)
{
// Load value into variable
value = parts[1];
// End the loop
break;
}
}
// Convert escape code
value = unescape(value);
// Convert "+"s to " "s
value.replace("+"," ");
// Return the value
return value;
}
// end hide -->
</script>
<script>
function saveDoc()
{
var docname= getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
}
if (docname != '') {
setCookie(docname,url,730);
}
else {
// Nothing else to do
}
</script>
它应该在用户单击此链接时创建:
<a href="#" onclick="saveDoc()" role="button" class="btn" data-toggle="tooltip" data-placement="bottom" id="save" title="" data-original-title="Save"><i class="icon-folder-open"></i></button>
我在答案的帮助下运行了一个错误脚本,它说 Uncaught referenceError setCookie not defined。
但是当另一个页面上的脚本检查它时,它不存在。
为什么不创建cookie?
像这样对吗?{
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;
alert(errorText);
}