在浏览器选项卡之间共享Cookie而不在javascript中刷新选项卡

时间:2016-07-15 07:03:52

标签: javascript cookies

您好我正在设计一个房地产网站,我有很多广告,我为每个广告添加了一个选项,如果用户点击"add to favorites"该广告的ID和网址保存在Cookie中并在"favorite page"中检索,因此用户可以在每次需要时查看该特定广告。我的每个广告都有一个这样的地址localhost/viewmore.php?ID=a number
在cookie中完全保存过程工作正常但最近我意识到了一些事情。考虑我使用此地址localhost/viewmore.php?ID=10访问我的一个广告并点击"add to favorite"然后如果我打开另一个包含此地址localhost/viewmore.php?ID=8的网页,然后我在"favorite page"我读取了我的Cookie会看到这个结果
[{"favoriteid":"10","url":"http://localhost/viewcookie.php?ID=10"},{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
这是完全正确的,这是我所期待的。

问题

现在考虑与之前的情况不同,我打开两个广告然后点击第一个广告上的"add to favorite",然后转到第二个广告(没有任何刷新),然后点击第二个广告上的"add to favorite"如果我在"favorite page"读取我的cookie,我会看到这个结果 [{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
这不是真的我希望两个人在我的cookie中看到广告的ID和网址,而不仅仅是最后一个。
ps:我使用push()方法将新对象添加到cookie数组中我认为每次点击后我都要更新它?任何想法谢谢



/*
  * Create cookie with name and value.
  * In your case the value will be a json array.
  */
  function createCookie(name, value, days) {
    var expires = '',
    date = new Date();
    if (days) {
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
  }
  /*
  * Read cookie by name.
  * In your case the return value will be a json array with list of pages saved.
  */
  function readCookie(name) {
    var nameEQ = name + '=',
    allCookies = document.cookie.split(';'),
    i,
    cookie;
    for (i = 0; i < allCookies.length; i += 1) {
      cookie = allCookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1, cookie.length);
      }
      if (cookie.indexOf(nameEQ) === 0) {
        return cookie.substring(nameEQ.length, cookie.length);
      }
    }
    return null;
  }
  function eraseCookie(name) {
    createCookie(name,"",-1);
}

    var faves = new Array();
	  function isAlready(){
    var is = false;
    $.each(faves,function(index,value){
      if(this.url == window.location.href){
        console.log(index);
          faves.splice(index,1);
          is = true;
      }
    });
    return is;
  }
$(function(){
var url = window.location.href; // current page url
    var favID;
    var query = window.location.search.substring(1);

	var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
	}
// this is the part i think i have to update every time without refreshing*******************************
	$(document.body).on('click','#addTofav',function(e){
		e.preventDefault();
	      if(isAlready()){
      } else {
          var fav = {'favoriteid':favID,'url':url};
          faves.push(fav);  
	}
//*******************************************************************************************************
	var stringified = JSON.stringify(faves);
    createCookie('favespages', stringified);
	});
  var myfaves = JSON.parse(readCookie('favespages'));
    if(myfaves){
    faves = myfaves;
    } else {
    faves = new Array();
    }

});
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的问题是您正在查看变量faves,它是在文档加载时初始化的,但它没有随着cookie的更改而更新。

第二页查看变量,从第一页看不到收藏夹,因为它实际上看不到cookie。

然后,它只是用它的值重置cookie。

以下是完整代码,其中添加了聊天功能:

/* 
 * Create cookie with name and value. 
 * In your case the value will be a json array. 
 */
function createCookie(name, value, days) {
  var expires = '',
    date = new Date();
  if (days) {
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  }
  document.cookie = name + '=' + value + expires + '; path=/';
}
/* 
 * Read cookie by name. 
 * In your case the return value will be a json array with list of pages saved. 
 */
function readCookie(name) {
  var nameEQ = name + '=',
    allCookies = document.cookie.split(';'),
    i,
    cookie;
  for (i = 0; i < allCookies.length; i += 1) {
    cookie = allCookies[i];
    while (cookie.charAt(0) === ' ') {
      cookie = cookie.substring(1, cookie.length);
    }
    if (cookie.indexOf(nameEQ) === 0) {
      return cookie.substring(nameEQ.length, cookie.length);
    }
  }
  return null;
}
/* 
 * Erase cookie with name. 
 * You can also erase/delete the cookie with name. 
 */
function eraseCookie(name) {
  createCookie(name, '', -1);
}

var faves = {
  add: function (new_obj) {
    var old_array = faves.get();

    old_array.push(new_obj);
    faves.create(old_array);
  },

  remove_index: function (index) {
    var old_array = faves.get();

    old_array.splice(index, 1);
    faves.create(old_array);
  },

  remove_id: function (id) {
    var old_array = faves.get();

    var id_index = faves.get_id_index(id);
    faves.remove_index(id_index);
  },

  create: function (arr) {
    var stringified = JSON.stringify(arr);
    createCookie('favespages', stringified);
  },

  get: function () {
    return JSON.parse(readCookie('favespages')) || [];
  },

  get_id_index: function (id) {
    var old_array = faves.get();

    var id_index = -1;
    $.each(old_array, function (index, val) {
      if (val.id == id) {
        id_index = index;
      }
    });

    return id_index;
  },

  update_list: function () {
    $("#appendfavs").empty();
    $.each(faves.get(), function (index, value) {
      var element = '<li class="' + index + '"><h4>' + value.id + '</h4> <a href="' + value.url + '">Open page</a> ' +
        '<a href="javascript:void(0);" class="remove" data-id="' + value.id + '">Remove me</a>';

      $('#appendfavs').append(element);
    });
  }
}

$(function () {
  var url = window.location.href;

  $(document.body).on('click', '#addTofav', function (e) {
    var pageId = window.location.search.match(/ID=(\d+)/)[1];

    if (faves.get_id_index(pageId) !== -1) {
      faves.remove_id(pageId);
    }
    else {
      faves.add({
        id: pageId,
        url: url
      });
    }

    faves.update_list();
  });

  $(document.body).on('click', '.remove', function () {
    var url = $(this).data('id');

    faves.remove_id(url);
    faves.update_list();
  });

  $(window).on('focus', function () {
    faves.update_list();
  });

  faves.update_list();
});