简体   繁体   English

如何通过cookie存储和重新加载动态表单?

[英]How to store and reload a dynamic form via cookies?

I have a form that the user can add rows to. 我有一个用户可以添加行的表单。 When that form is submitted I need to store those values in cookies so I can reload the form when the page refreshes or the user leaves the site and returns. 提交该表单时,我需要将这些值存储在cookie中,以便在页面刷新或用户离开站点并返回时重新加载表单。 I've already got the form being built from javascript and am looking for some sort of js or php tool that will automatically store and reload forms, including dya=namic generation of forms. 我已经有了从javascript构建的表单,我正在寻找某种js或php工具,它将自动存储和重新加载表单,包括dya = namic生成的表单。

Thanks! 谢谢!

Seems like you should be able to use jquery's built in form serializer, and then save that in a cookie. 看起来你应该能够使用jquery的内置表单序列化程序,然后将其保存在cookie中。

//here's a little helper function to set a cookie

function setCookie(key, value, daysUntilExpiration) {
    var expiration = new Date();
    expiration.setTime(expiration.getTime()+(daysUntilExpiration*86400000));

    document.cookie = key + "=" + value + ";expires=" + expiration.toGMTString() + ";path=/";
}

//first, get the serialized data from your dynamic form
var formData = $("#myform").serialize();

//then, save it into a cookie
setCookie("myform", formData, 30); //cookie saved for 30 days

To pull it back out, you should be able to simply split on the key/value with the "=" as the split character, then loop through each one, and build out the form HTML. 要将其拉出来,您应该能够简单地将键/值拆分为“=”作为拆分字符,然后循环遍历每个键,并构建表单HTML。

You may use PHP's setcookie() function to save these. 您可以使用PHP的setcookie()函数来保存它们。 Here's a few simple functions to do what you want. 这里有一些简单的功能可以做你想要的。 However, this will only work with inputs that have values. 但是,这仅适用于具有值的输入。 It will not work with selects. 它不适用于选择。 Make sure each input has a different name, otherwise this will not work. 确保每个输入都有不同的名称,否则这将无效。

function SaveAll() {
    $cookie_expires = 14; // how many days until the cookies expire
    foreach($_POST as $col => $val) {
        setcookie("form_".strtolower($col), $val, time()+(64000 * $cookie_expires));
    }
}

function Load($item) {
    $item = strtolower($item);
    if(!$_COOKIE['form_'.$item]) return null;
    return $_COOKIE['form_'.$item];
}

if($_POST['submit_button_name']) {
    SaveAll();
    echo "All inputs have been saved! <BR><BR>";
}

Then simply add things like this to all your inputs. 然后只需在所有输入中添加这样的内容即可。

<input name="Item01" value="<?=Load('Item01');?>" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM