在Cookie中存储表单值

时间:2012-05-14 09:02:03

标签: php javascript forms cookies setcookie

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

我没有太多运气,我发现的所有例子都没有帮助。 我应该使用PHP还是JS生成它们? 任何反馈或正确方向的踢都将受到高度赞赏!

http://jsfiddle.net/yucM7/

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式使用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: $.cookie("example", "foo");

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

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

答案 1 :(得分:2)

这里是example

您只需要jQuery和cookie plugin

请记住,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;
});