jQuery - 我可以从序列化表单字符串填充表单输入吗?
鉴于我在页面上有某种形式,我知道我可以使用以下命令获取 unicode 序列化字符串。
var query = jQuery('#some-form').serialize();
也可以使用 $('#some-input').val(...)< 设置每个输入的值/代码>。假设重置了上面相同的表单,但我仍然有查询字符串 - 有没有一种简单的方法可以从该字符串填充表单?我意识到我可以解析它并单独设置每个输入/选择,但我正在寻找一个更简单的解决方案。谢谢。
Given that I have some form on a page, I know I can get a unicode serialized string using
var query = jQuery('#some-form').serialize();
It's also possible setting the value of each input with $('#some-input').val(...)
. Assuming that same form above was reset, but I still have the query string - is there a simple way to populate the form from that string? I realize I could parse it and set every input/select individually, but I was looking for a simpler solution. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将表单序列化为 JSON 数组,并使用 MVVM 映射插件(如 Knockout.js)自动填充形式。
请参阅在 jQuery 中序列化为 JSON
You could serialize the form into a JSON array and use an MVVM mapping plugin like Knockout.js to auto-fill the form.
See Serializing to JSON in jQuery
jquery.deserialize 插件 应该可以帮助你。
jquery.deserialize plugin should help you.
如果您的表单仅包含文本输入(不是数组),您可以尝试这个插件,我从其反序列化函数对应项(https://gist.github.com/rcmachado/242617#file-jquery-unserialize-js),但它不是返回对象,而是填充其适用的表单。
使用示例:
显然,您首先需要将表单保存在 sessionStorage 中。
例子:
If your form only contains text inputs (not as arrays), you may try this plugin, which I've adapted from its unserialize function counterpart (https://gist.github.com/rcmachado/242617#file-jquery-unserialize-js), but instead of returning an object, it fills the form it applies to.
Example of use:
Obviously you'll need to have saved your form in the sessionStorage in the first place.
Example: