Javascript jQuery:从参数字符串设置窗体状态
我需要将表单的状态保存在cookie中,这样就可以记住给定用户的设置。我正在使用jQuery,因此我的计划是:Javascript jQuery:从参数字符串设置窗体状态,javascript,jquery,forms,cookies,params,Javascript,Jquery,Forms,Cookies,Params,我需要将表单的状态保存在cookie中,这样就可以记住给定用户的设置。我正在使用jQuery,因此我的计划是: Saving: //generate a param string from the form settings var paramString = $.param($("#my-form").serializeArray()); //save it to a cookie $.cookie("my-form-cookie", paramString); Loading: //get
Saving:
//generate a param string from the form settings
var paramString = $.param($("#my-form").serializeArray());
//save it to a cookie
$.cookie("my-form-cookie", paramString);
Loading:
//get the cookie value
var savedParams = $.cookie("my-form-cookie")
//turn it into an object with field names as keys and field values as values
var formObject = JSON.parse('{"' + decodeURI(savedParams).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
//go through this, modifying the form
...
这是目前拼图中缺失的一块
我计划做的是这样的事情(伪代码而不是js)
在我开始编写一个函数来完成这项工作之前,它采用了一个表单id和一个param样式的字符串,我认为其他人要么a)以比我更彻底的方式完成了这项工作,要么b)尝试过并认为这是一个坏主意,要么注定要失败
有人有任何意见吗,关于a)或b)
谢谢!max以下是我最后做的事情。它有一定的清理空间,但似乎还可以。它处理嵌套参数和数组样式参数。您可以添加一个
dont cookie
类,以形成您不希望从cookie中设置的元素,当它用于恢复状态时
//convert the form's state to a params string and save it to a cookie with the
//name form-<form_id>. Note that all form values are saved to
//the cookie, even the ones with .dont-save (these are ignored on load though)
function saveFormStateToCookie(form, cookie){
//jqueryfy the form if it's not already
if(typeof(form) != "object")
form = $(form);
if(typeof(cookie) == "undefined")
cookie = formCookieName(form);
//console.log("using cookie name '"+cookie+"'");
var paramString = $.param(form.serializeArray());
//console.log("saving: (unescaped)\n"+unescape(paramString));
$.cookie(cookie, paramString, {path: "/"});
}
function loadFormStateFromCookie(form, cookie){
//jqueryfy form if it's not already
if(typeof(form) != "object")
form = $(form);
if(typeof(cookie) == "undefined")
cookie = formCookieName(form);
//console.log("using cookie name '"+cookie+"'");
//get the cookie value
var paramString = $.cookie(cookie);
//console.log("loaded:(unescaped)\n"+unescape(paramString));
//what if it's blank, or the cookie doesn't exist?
if(paramString){
//turn it into an object with field names as keys and field values as values
var formObject = QueryStringToHash(paramString);
var elements, checkableElements, matchedElement;
var changedElements = [];
//set all checkboxes and radio buttons in the form to be blank
form.find("[type='radio'], [type='checkbox']").not(".dont-cookie").removeAttr('checked');
//go through this, modifying the form
$.each(formObject, function(name,values){
//note: value can be an array of values or a string. Let's make it always an array, to be consistent
if(typeof(values) === "string"){
values = [values];
}
//find all elements matching the name.
elements = form.find("[name='"+name+"']").not(".dont-cookie");
if(elements.size() > 0){
//iterate over values
$.each(values, function(i,value){
//is there a checkbox/radio with this value, which ISN'T in changedElements?
var checkboxes = elements.filter("[type='radio'], [type='checkbox']").filter("[value='"+value+"'], [value='"+value.replace(/\+/g, " ")+"']").filter(function(i){ return changedElements.indexOf($(this)) === -1});
//yes there is - check it and add it to changedElements
if(checkboxes.size() > 0){
$.each(checkboxes, function(j,checkbox){
checkbox = $(checkbox);
checkbox.attr("checked", "checked");
changedElements.push(checkbox);
});
} else {
//THIS IS WIPING OVER ALL THE CHECKBOXES: WE NEED TO JUST DO IT TO NON-CHECKBOXES
//no there isn't: set their val to value, then add them to changedElements
$.each(elements.not("[type='radio'], [type='checkbox']"), function(i, element){
element = $(element);
element.val(value);
changedElements.push(element);
});
}
});
}
});
} else {
//console.log("Couldn't find a cookie matching "+cookie);
}
}
//将表单状态转换为params字符串,并使用
//姓名表格-。请注意,所有表单值都保存到
//cookie,即使是带有.dont save的cookie(但在加载时会忽略这些cookie)
函数saveFormStateTookie(表单,cookie){
//jqueryfy表单(如果还没有)
if(typeof(form)!=“object”)
表格=$(表格);
if(类型(cookie)=“未定义”)
cookie=formCookieName(表单);
//log(“使用cookie名称“'+cookie+””);
var paramString=$.param(form.serializeArray());
//log(“saving:(unescaped)\n”+unescape(paramString));
$.cookie(cookie,paramString,{path://“});
}
函数loadFormStateFromCookie(表单,cookie){
//jqueryfy表单(如果还没有)
if(typeof(form)!=“object”)
表格=$(表格);
if(类型(cookie)=“未定义”)
cookie=formCookieName(表单);
//log(“使用cookie名称“'+cookie+””);
//获取cookie值
var paramString=$.cookie(cookie);
//log(“已加载:(未加载)\n”+unescape(paramString));
//如果它是空的,或者cookie不存在怎么办?
if(参数字符串){
//将其转换为一个对象,字段名作为键,字段值作为值
var formObject=QueryStringToHash(paramString);
变量元素、可检查元素、匹配元素;
var changedElements=[];
//将表单中的所有复选框和单选按钮设置为空
form.find(“[type='radio'],[type='checkbox']”)。not(“.dont cookie”)。removeAttr('checked');
//完成此操作,修改表单
$.each(表单对象、函数(名称、值){
//注意:值可以是值的数组或字符串。为了保持一致,让我们将其始终设置为数组
if(类型(值)=“字符串”){
值=[值];
}
//查找与名称匹配的所有元素。
elements=form.find(“[name=”+name+“]”)。而不是(“.dont cookie”);
如果(elements.size()>0){
//迭代值
$。每个(值,函数(i,值){
//是否有具有此值的复选框/单选框,而该值不在changedElements中?
var复选框=elements.filter(“[type='radio'],[type='checkbox']”)。filter(“[value=”“+value+”],[value=”+value.replace(/\+/g,““+”)”+“]”)。filter(函数(i){return changedElements.indexOf($(this))====-1});
//有-检查并将其添加到changedElements
如果(复选框.size()>0){
$.each(复选框,函数(j,复选框){
复选框=$(复选框);
checkbox.attr(“checked”、“checked”);
changedElements.push(复选框);
});
}否则{
//这是在清除所有的复选框:我们只需要对非复选框这样做
//不,没有:将它们的val设置为value,然后将它们添加到changedElements
$.each(elements.not(“[type='radio'],[type='checkbox']”),函数(i,element){
元素=$(元素);
元素val(值);
changedElements.push(元素);
});
}
});
}
});
}否则{
//log(“找不到与“+cookie”匹配的cookie);
}
}
您是否可以使用从cookie中获得的信息从服务器发送此数据,而不是cookie?如果你能做到这一点,那么你可以用一些mvvm框架(angular、knockout和c)填充表单。但这很复杂——我真的很想使用js在客户端保存和加载状态。
//convert the form's state to a params string and save it to a cookie with the
//name form-<form_id>. Note that all form values are saved to
//the cookie, even the ones with .dont-save (these are ignored on load though)
function saveFormStateToCookie(form, cookie){
//jqueryfy the form if it's not already
if(typeof(form) != "object")
form = $(form);
if(typeof(cookie) == "undefined")
cookie = formCookieName(form);
//console.log("using cookie name '"+cookie+"'");
var paramString = $.param(form.serializeArray());
//console.log("saving: (unescaped)\n"+unescape(paramString));
$.cookie(cookie, paramString, {path: "/"});
}
function loadFormStateFromCookie(form, cookie){
//jqueryfy form if it's not already
if(typeof(form) != "object")
form = $(form);
if(typeof(cookie) == "undefined")
cookie = formCookieName(form);
//console.log("using cookie name '"+cookie+"'");
//get the cookie value
var paramString = $.cookie(cookie);
//console.log("loaded:(unescaped)\n"+unescape(paramString));
//what if it's blank, or the cookie doesn't exist?
if(paramString){
//turn it into an object with field names as keys and field values as values
var formObject = QueryStringToHash(paramString);
var elements, checkableElements, matchedElement;
var changedElements = [];
//set all checkboxes and radio buttons in the form to be blank
form.find("[type='radio'], [type='checkbox']").not(".dont-cookie").removeAttr('checked');
//go through this, modifying the form
$.each(formObject, function(name,values){
//note: value can be an array of values or a string. Let's make it always an array, to be consistent
if(typeof(values) === "string"){
values = [values];
}
//find all elements matching the name.
elements = form.find("[name='"+name+"']").not(".dont-cookie");
if(elements.size() > 0){
//iterate over values
$.each(values, function(i,value){
//is there a checkbox/radio with this value, which ISN'T in changedElements?
var checkboxes = elements.filter("[type='radio'], [type='checkbox']").filter("[value='"+value+"'], [value='"+value.replace(/\+/g, " ")+"']").filter(function(i){ return changedElements.indexOf($(this)) === -1});
//yes there is - check it and add it to changedElements
if(checkboxes.size() > 0){
$.each(checkboxes, function(j,checkbox){
checkbox = $(checkbox);
checkbox.attr("checked", "checked");
changedElements.push(checkbox);
});
} else {
//THIS IS WIPING OVER ALL THE CHECKBOXES: WE NEED TO JUST DO IT TO NON-CHECKBOXES
//no there isn't: set their val to value, then add them to changedElements
$.each(elements.not("[type='radio'], [type='checkbox']"), function(i, element){
element = $(element);
element.val(value);
changedElements.push(element);
});
}
});
}
});
} else {
//console.log("Couldn't find a cookie matching "+cookie);
}
}