首页 > 解决方案 > 设置 cookie 并在多次访问时重定向未按预期工作

问题描述

我创建了一个脚本,在我看来应该可以工作,但不幸的是,即使满足条件,它也设置了 cookie2 的问题。

<script type="text/javascript">
    jQuery(document).ready(function () {
        if (typeof Cookies.get('cookie1') !== 'undefined') {
            Cookies.set('cookie2', 'true', {expires: 1000});
            window.location.href = "https://google.com/second";
        }
        else
        {
            Cookies.set('cookie1', 'true', {expires: 1000});
            }
            window.location.href = "https://google.com/first";
        }
    });
</script>

    <script type="text/javascript">
    jQuery(document).ready(function () {
        if (typeof Cookies.get('cookie2') !== 'undefined') {

            window.location.href = "https://google.com/third";
        }
        else
        {
        }
    });
</script>

用户第一次访问应该访问 google.com/first,用户第二次访问应该访问 google.com/second,最后一次访问应该访问 google.com/third。第二次访问没有得到满足,因为看起来像 cookie 2 已经被插入,即使它不在第一个“else”函数中

标签: javascriptcookiessetcookie

解决方案


嗨,问题在于您的 if/else 条件的条件说明。它将始终进入 else 条件,因为在第一页加载后为cookie1设置了该值

window.location.href = " https://google.com/first ";

所以你需要添加嵌套的 if/else 条件

小提琴链接:https ://jsfiddle.net/kju86Ly9/3/

jQuery(document).ready(function () {
    console.log(getCookie('cookie1'))
    console.log(getCookie('cookie2'))

	if (getCookie('cookie1') !== 'undefined' && getCookie('cookie2') === null) {
        setCookie('cookie2', 'true', 10);
        console.log('https://google.com/first')
		window.location.href = "https://google.com/first";
	} else if (getCookie('cookie2') !== 'undefined' && getCookie('cookie3') === null) {
        setCookie('cookie3', 'true', 10);
        console.log('https://google.com/second')

		window.location.href = "https://google.com/second";
	} else {
        console.log('https://google.com/third')

		window.location.href = "https://google.com/third";
	}


	function setCookie(name, value, days) {
		var expires = "";
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = "; expires=" + date.toUTCString();
		}
		document.cookie = name + "=" + (value || "") + expires + "; path=/";
	}

	function getCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
    }
    function eraseCookie(name) {   
        document.cookie = name+'=; Max-Age=-99999999;';  
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>


推荐阅读