使用表单的当前状态序列化和反序列化表单

Serializing and deserializing a form with its current state

本文关键字:表单 序列化 状态 反序列化      更新时间:2023-09-26

我有这个表格

<form id=my_form>
    <input id=mt type=text><input id=mc type=checkbox><textarea id=mta /> 
</form>

我想在其他地方有一个按钮,它可以序列化表单及其状态,也就是说,如果文本区域有内容,或者文本有内容或按下复选框,我希望该信息以某种方式存储在字符串中。稍后,我想使用该字符串恢复表单中的信息。

我尝试使用.innerHTML,但它不起作用,我总是得到原始的HTML。

我还查看了jQuery的序列化方法,但我无法在表单"内部"反序列化它。

提前谢谢你!

库尔特

我已经为你做了一些例子。经过测试 - 工作正常。你需要jQuery库首先是表格:

<form id="my_form">
    <input id="formText" type="text" name="formText" />
    <br />
    <label><input id="formCheck" type="checkbox" name="formCheck" /> check 1</label>
    <br />
    <label><input id="formCheck2" type="checkbox" name="formCheck2" /> check 2</label>
    <br />
    <textarea name="formTextarea" id="formTextarea" cols="20" rows="3"></textarea> 
    <br />
    <label><strong>Time unit</strong>:</label>
    <p>
        <label><input type="radio" name="dataView" value="week" checked="checked" /> Week</label>
        <label><input type="radio" name="dataView" value="month" /> Month</label>
        <label><input type="radio" name="dataView" value="year" /> Year</label>
    </p>

    <input type="button" value="Serialize" onclick="serializeForm()" />
    <input type="button" value="Unserialize" onclick="restoreForm()" />
</form>

点击按钮后,在 js
中调用相应的函数这是js:序列化数据存储在变量formData,如果需要,您可以将其存储在cookie,数据库等中。然后根据您的要求加载它

<script type="text/javascript">
    var formData;            
    function  serializeForm() {
        formData = $('#my_form').serialize();
    }           
    function restoreForm() {
        var obj = unserializeFormData(formData);
        // Restore items one by one
        if(obj.hasOwnProperty('formTextarea')) {
            $('#formTextarea').val(obj.formTextarea);
        }
        if(obj.hasOwnProperty('formText')) {
            $('#formText').val(obj.formText);
        }
        // Radio buttons
        if(obj.hasOwnProperty('dataView'))
            $('input[value="'+obj.dataView+'"]').attr('checked', true);

        // Restore all checkbox. You can also iterate all text fields and textareas together, because the have same principle for getting and setting values by jQuery 
        $('#my_form input[type="checkbox"]').each(function(){
            var checkName = $(this).attr('name');
            var isChecked = false;
            if(obj.hasOwnProperty(checkName))
                isChecked = true;
            $(this).attr('checked',isChecked); 
        });
    }            

    function unserializeFormData(data) {
        var objs = [], temp;
        var temps = data.split('&');
        for(var i = 0; i < temps.length; i++){
            temp = temps[i].split('=');
            objs.push(temp[0]);
            objs[temp[0]] = temp[1]; 
        }
        return objs; 
    }
</script>