设置cookie并重定向多次访问,但无法按预期进行

时间:2019-08-03 15:26:33

标签: javascript cookies setcookie

我创建了一个脚本,该脚本看起来应该可以工作,但不幸的是,即使满足条件,它也会设置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”函数中

1 个答案:

答案 0 :(得分:1)

嗨,问题在于您的if / 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>