为什么我的Cookie会随机变化?

时间:2015-07-14 06:02:18

标签: javascript jquery ruby-on-rails cookies

简介

我正在开发一个带有Rails 4的应用程序,它作为一个简单的仪表板,它遍历几个div容器,在主页上的象限中划分出来,显示各种图形/表格等。我正在使用cookie来记住哪个索引当前显示的容器处于这样的状态,当网站重新加载时,它会显示正在显示的容器,而不会返回到第一个容器。

问题

在我开始注意到cookie开始自行更改并且我不知道如何改变之前,一切似乎都正常工作。我得出了这个结论,因为我使用一个函数设置并获取cookie,无论何时调用它都会打印到控制台。当这些“流氓”变化发生时,没有任何东西被记录到控制台。

这是它如何运作的要点。更新函数使用辅助函数来获取cookie,根据当前索引计算下一个索引,然后调用另一个辅助函数来存储cookie。只有这两个功能才能获取和设置cookie。

var update_quadrant = function(id) = 
 $.when(get_cookie(current_feed)).done(function(response) {
      var current_index = parseInt(response);
      var next_index = //depends on current_index
     $.when(store_cookie(current_feed, next_index, "from update")).done(function(response){
          //code that updates quadrant 
          setTimeout(function() { update_quadrant(id);}, 30000);
      });

这是一些典型的cookie的样子。

{"circleci" => "0", "newrelic" => "1", "googleanalytics" => "0"}

的Javascript

存储Cookie值

var store_cookie = function(feed, value, other) {
return $.ajax({
    url: 'home/cookie_store',
    type: 'POST',
    data: {
        feed: feed,
        value: value,
        other: other || ""
    }
    }).done(function(response) {
    console.log(response);
    });
};

获取cookie

var get_cookie = function(feed) {
    return $.ajax({
        url: 'home/cookie_get',
        data: {
            feed: feed
        }
    }).done(function(response) {
    console.log("Got cookie value: ", parseInt(response), "for ", feed);
    });
};

控制器

响应ajax调用存储cookie值

#home controller
 def store_cookie
    feed = params[:feed]
    value = params[:value]
    other = params[:other]
    cookies[feed] = value.to_s
    render text: "stored #{value} for #{feed}, other: #{other}"
 end

响应ajax调用cookie值。

#home controller
 def give_cookie 
    feed = params[:feed]
    cookies[feed] = "0" if cookies[feed].blank?
    render text: cookies[feed.to_s]
 end

我试图测试的内容

我认为也许某种程度上setTimeout函数是持久的,并且正在执行多个setTimeout计时器,但这并没有改变值发生变化而没有从store_cookie函数记录到控制台的事实。

例如,我设置setInterval每秒将document.cookie记录到控制台。这是将要显示的内容。

 "Stored 0 for circleci, other: from update quadrant" 
//correctly changed with store_cookie function as it logs the response from the controller
{"circleci" => "0", "newrelic" => "1", "googleanalytics" => "0"}
...//no change
...//no change
...//no change
{"circleci" => "1", "newrelic" => "1", "googleanalytics" => "0"}
//but nothing printed to console from store_cookie function 
//quadrant eventually goes to update after 30 seconds, and gets wrong cookie value
"Got cookie value: 1 for circleci" //should be 0 not 1

更令人费解的是,当我点击使用不包含任何javascript源文件的布局的链接时,cookie值仍然被更改。

我一直在努力想知道从哪里开始调试这个,因为我进行了双重和三重检查,以确保代码端的所有cookie更改都通过我的store_cookie函数更改,并且我看到这些cookie值正在更改没有任何记录到控制台,也没有调用store_cookie函数。

有没有人知道什么导致我的cookie值似乎自己发生变化?

0 个答案:

没有答案
相关问题