将表单值存储在 Cookie 中

Jam*_*sil 3 javascript php forms cookies setcookie

在过去的几个小时里,我一直在尝试自学有关 cookie 的知识,以及如何将几个表单字段中的值存储到 cookie 中。

我运气不太好,我发现的所有例子都没有太大帮助。我应该使用 PHP 还是 JS 生成它们?任何反馈或正确方向的推动将不胜感激!

http://jsfiddle.net/yucM7/

提前致谢!

Kan*_*hen 5

这是一个例子

您所需要的只是 jQuery 和cookie 插件

请记住,html 代码中有一些更改。

$(document).on('submit', '#myForm', function() {
   // serialize our form (get string containing field names and values)
   dataString = $(this).serialize();
   // set new cookie
   $.cookie('formCookie', dataString);
   return false;
});

$(document).on('click', '#getCookie', function() {
   // get serialized string from cookie    
   cookieData = $.cookie('formCookie');
   // if cookie exists continue
   if (cookieData != null) {
        // split cookieData string into an array of fields and their values
        cookieArray = cookieData.split('&');
        // go through each field and split it too to get field name and it's value
        $.each(cookieArray, function(k, v) {
          field = v.split('=');
          // populate field with data
          $('#myForm [name="'+field[0]+'"]').val(field[1]);
        });
    }
   return false;
});
Run Code Online (Sandbox Code Playgroud)