问题描述
是否有任何方法可以将表单状态存储在例如cookie中并进行检索?
我检查了序列化API ,但是我不知道如何在表单上检索序列化的数据.
有可能吗?
Is there any way to store form state in for example cookie and retrieval it ?
I checked serialize API but I have no idea how to retrieval serialized data on the form.
Is it possible?
我在此处放置了我的代码.检查Cookie////Cookie插件结束后,因为我确信jQuery插件可以正常工作.
I putted my code here. Check the javascript code after // End of cookie plugin becasue I am sure that jQuery plugin works right.
推荐答案
是的,您可以使用serialize()
序列化表单值.语法:
Yes, you can serialize form values with serialize()
.Syntax:
$("#your_form").serialize()
将返回一个您可以处理或保存到cookie的字符串(您可以使用jquery cookie插件).
will return a string you can handle, or save to cookie (you can use the jquery cookie plugin).
编辑: 上面的代码将序列化,但是将很难检索.
您最好使用serializeArray()
,它返回一个名称/值对数组(例如:[{name: "age", value: "23"}, {name: "sex", value: "male"}]
).您可以查看文档以获得更好的解释.
EDIT: The above code will serialize, but will be hard to retrieve.
You should better use serializeArray()
, which returns an array of name value pairs ( like: [{name: "age", value: "23"}, {name: "sex", value: "male"}]
). You can see the docs for better explanation.
有了这一点,我们可以构建一个从窗体到字符串"功能和一个从字符串到窗体"功能:
With that, we can build a "form to string" function and a "string back to form" function:
function form2string($form) {
return JSON.stringify($form.serializeArray());
}
function string2form($form, serializedStr) {
var fields = JSON.parse(serializedStr);
for(var i = 0; i < fields.length; i++){
var controlName = fields[i].name;
var controlValue = fields[i].value;
$form.find('[name=' + controlName + ']').val(controlValue);
}
}
使用form2string对其进行序列化,并使用string2form将字符串设置回该表单.要存储和检索序列化,可以使用 cookie插件.
Use form2string to serialize it and string2form to set the string back to the form. To store and retrive the serialization, you can use the cookie plugin.
希望这会有所帮助.干杯
Hope this helps. Cheers
PS:JSON方法仅在现代浏览器中有效
PS: JSON methods will work only in modern browsers
这篇关于jQuery存储和检索表单状态(带有数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!