将表单值存储在 Cookie 中

Store Form Values In Cookie

本文关键字:Cookie 存储 表单      更新时间:2023-09-26
在过去的

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

我运

气不好,我找到的所有例子都不是很有帮助。我应该使用 PHP 还是 JS 生成它们?任何反馈或朝着正确方向踢球将不胜感激!

http://jsfiddle.net/yucM7/

提前感谢!

下面是

一个示例。

您所需要的只是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;
});

您可以使用Javascript通过以下方式设置cookie(请参阅 http://www.w3schools.com/js/js_cookies.asp):

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

使用 Jquery: $.cookie("example", "foo"); 设置 cookie

或者,您可以通过以下方式从服务器设置cookie:

<?php
    $value = 'something from somewhere';
    setcookie("TestCookie", $value);