1

我意识到 FireFox、Chrome、Safari 和 Opera 可以限制域/网站可以设置的 cookie 数量。所以我想到了一种不同的方法来存储我的 Web 表单许多文本、单选按钮和选择框值 - 为 Web 表单的每个主要部分设置一个多变量 cookie,而不是为每个变量设置一个单独的 cookie。

它看起来像这样(在每个 cookie 内容中)......

firstName=John;&&;lastName=Andrews;&&;streetAddress=1234 Memory Ln.

我正在寻找的是一个 JavaScript 函数,它将正确地创建/更新这种类型的 cookie(使用元素名称而不是 ID 以获得与单选按钮的最大兼容性),在每个表单元素的“onchange”事件上触发。

然后在需要时,一个函数将 cookie 加载到 JavaScript 字符串变量中,从 ';&&;' 之间解析实际变量的字符串 并通过相应的名称将它们加载到真正的 JavaScript 变量中,然后当用户返回表单时,JavaScript 会自动用这些值填充相应(同名)表单元素的值。

任何帮助将不胜感激。

提前致谢!!

——詹姆斯·A。

4

1 回答 1

1

下面是完整的解决方案:这是完整的“save_form.js”代码!

//<!-- Prerequisites: jquery.min.js -->

//<!-- A script to set a cookie [Argument(s) accepted: Cookie Name, Cookie Value, etc.] [BEGIN] -->
function set_cookie ( name, value, path, domain, secure )
    {
        var cookie_string = name + "=" + escape ( value );

        var cookie_date = new Date();  // current date & time ;

        var cookie_date_num = cookie_date.getTime(); // convert cookie_date to milliseconds ;
        cookie_date_num += 35 * 60 * 1000;  // add 35 minutes in milliseconds ;
        cookie_date.setTime(cookie_date_num); // set my_date Date object 35 minutes forward ;


        cookie_string += "; expires=" + cookie_date.toGMTString();


        if ( path )
            cookie_string += "; path=" + escape ( path );

        if ( domain )
            cookie_string += "; domain=" + escape ( domain );

        if ( secure )
            cookie_string += "; secure";

        document.cookie = cookie_string;

    };
//<!-- A script to set a cookie [Argument(s) accepted: Cookie Name, Cookie Value, etc.] [END] -->

//<!-- A script to grab a cookies value by name [Argument(s) accepted: Cookies Name] [BEGIN] -->

function get_cookie ( cookie_name )
    {
        var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

        if ( results )
            { 
            return ( unescape ( results[2] ) ); 
            }
    else
            {
            return null;
            };
    };

//<!-- A script to grab a cookies value by name [Argument(s) accepted: Cookies Name] [END] -->


function populateCookieFromForm ( cookieName ) {

    var encodedCookie;

    var preCookieObj = '{';

    var allMainElements = $('form').find('input[type=text], select');

    for (var i=0; i < allMainElements.length; i++) 
        {

            preCookieObj = preCookieObj + '"' + allMainElements[i].name +'":"'+ allMainElements[i].value +'",';     

        };

    preCookieObj = preCookieObj.substring(0, preCookieObj.length - 1);
    preCookieObj = preCookieObj + '}';

    //<!-- btoa() encodes 'string' argument into Base64 encoding --> 
    encodedCookie = btoa( preCookieObj );

    set_cookie(cookieName, encodedCookie);

};

function populateFormFromCookie (cookieName) {


    if ( ! get_cookie ( cookieName ) )

        {

        //<!-- Do Nothing - No Cookie For this form set. -->

        }
    else 
        {
            //<!-- atob() decodes 'string' argument from Base64 encoding --> 
            jSONCookieObj = atob( get_cookie ( cookieName ) ) ;     

            jSONObj = JSON.parse( jSONCookieObj );

            var allMainElements = $('form').find('input[type=text], select');

            for (var i=0; i < allMainElements.length; i++)  
            {

                var elementName = allMainElements[i].name;

                var elementValue = jSONObj[elementName];

                allMainElements[i].value = elementValue;

            };

        };


};


function populateCookieFromRadios (cookieName) {
    var radioState={};

    $(':radio').each(function(){
    if(!radioState[this.name]){
    radioState[this.name]={};
    }    
    radioState[this.name][this.value]=this.checked;
    });


    /* stringify to JSON and convert to Base64 */
    var storeString= btoa(JSON.stringify(radioState));

    /* store in cookie*/
    set_cookie(cookieName, storeString);

};


function populateRadiosFromCookie (cookieName) {

    if ( ! get_cookie ( cookieName ) )

        {

        //<!-- Do Nothing - No Cookie For this form set. -->

        }

    else
        {

            var cookieString = get_cookie ( cookieName );
            var newPageState= JSON.parse(atob(cookieString));

            /* loop through radios setting state */
            $(':radio').prop('checked',function(){
            return newPageState[this.name][this.value];    
            });

        };
};

这就是您正确调用这些函数的方式。在包含表单的 HTML/PHP 页面的底部附近,分别放置此 JavaScript:

<script type="text/javascript">

//<!-- If returning user detected, populate form with cookie values [BEGIN] -->

populateFormFromCookie('thisForm');
populateRadiosFromCookie('thisFormRadios');
//<!-- If returning user detected, populate form with 'section' cookie values [END] -->

//<!-- On change of ALL form elements re-save form cookie(s) [BEGIN] -->

$('input[type=radio]', $('form')).on('change',function(e){

        populateCookieFromRadios('thisFormRadios');

    });

$('input[type=text], select, textarea', $('form')).on('change',function(e){

        populateCookieFromForm('thisForm');

    });

$('input[type=text]', $('form')).on('input',function(e){     

        populateCookieFromForm('thisForm');

    });
//<!-- On change of ALL form elements re-save form cookie(s) [END] -->

</script>

下一个任务是看看是否所有这些都可以在没有 jQuery 的情况下完成......嗯......

于 2013-11-15T06:54:48.717 回答