【问题标题】:javascript to remember user choice for country & city then they should redirect to a pagejavascript 来记住用户对国家和城市的选择,然后他们应该重定向到一个页面
【发布时间】:2016-04-01 11:41:43
【问题描述】:

我需要一个 JavaScript 代码 sn-p 来记住用户的选择(与 cookie 一起存储)。一旦用户选择了国家和城市,他们应该被重定向到一个特定的页面,这取决于之前的选择。

他们还可以随时更改国家和城市。

【问题讨论】:

  • 祝你好运,你已经知道你需要 cookie,所以最好开始编码!
  • 您应该接受您的问题。开始编码。
  • 澄清问题
  • 我不知道任何代码。我对此知之甚少。请给我代码。谢谢你

标签: javascript html redirect cookies url-redirection


【解决方案1】:
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));  //set d to x days (e.g. 30 days (= 2592000 seconds))
    var expires = "expires="+d.toUTCString();         //set to valid date
    document.cookie = cname + "=" + cvalue + "; " + expires;  //set cookie
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';'); //put all the cookies in the document into an array, called 'ca'
    for (var i=0; i<ca.length; i++) {    //for each cookie
        var c = ca[i];                   //set 'c' to that cookie
        while (c.charAt(0)==' ') c = c.substring(1);  //get rid of superfluous characters
        if (c.indexOf(name) == 0)  //if 'c' == 'cname' (e.g. the cookie you're checking for
            return c.substring(name.length,c.length);  //return the value of that cookie
    }
    return "";
}

function onSelect(country, city) {
   //call this function when the user has selected their country and city
    setCookie("country", country, 30);
}

if (getCookie("country") && getCookie("city")) {
    //this function will run automatically at first,
    //if the user has already selected country and city (i.e. those cookies already exist)
        //redirect to specific page
}

本文改编自http://www.w3schools.com/js/js_cookies.asp

【讨论】:

  • 请提供完整的代码,包括 html,因为我是初学者。谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多