Установите и обновите глобальный файл cookie jQuery - PullRequest
0 голосов
/ 09 октября 2019

Я создаю сайт, который устанавливает множество файлов cookie в зависимости от выбора. Файл cookie обновляется и сохраняется, но когда я перехожу на другую страницу, выборы не сохраняются глобально. Я попытался использовать путь: /, и он запоминает только варианты, когда я захожу на эту страницу.

Я храню файл cookie, который отображает список на панели выбранных параметров и также хранится в скрытом поле.

У меня есть код ниже, путь в правильном месте?

jQuery(document).ready(function () {

    jQuery("ul.activities_list").append(jQuery.cookie("listItem"), {
                expires: 7,
                path: '/'
            }); //<---end of $.cookie);
  jQuery(".activity").on("click", ".add_activity", function() {

   // jQuery(".add_activity").live('click',function () {
        var title = jQuery(this).parent().parent().find('.title').html();

        // Add activity item to the panel list.
        jQuery("ul.activities_list").prepend(jQuery('<li>'+title+'<button id="remove_item" class="button is-primary is-white">Remove</button></li>'));

        jQuery.cookie("listItem", ((jQuery.cookie("listItem") ? jQuery.cookie("listItem") : '') + jQuery('<li>'+title+'<button id="remove_item" class="button is-primary is-white">Remove</button></li></li>').clone().wrap('<div />').parent().html(), '/'));
        jQuery.cookie("listItemTitle", ((jQuery.cookie("listItemTitle") ? jQuery.cookie("listItemTitle") : ', ') + title));
   console.log(jQuery.cookie("listItem")) });
    jQuery("#remove_item").live('click',function () {

        jQuery(this).parent().remove();
        var removed_item = jQuery('.activities_list').html();

        jQuery.cookie("listItem", removed_item);
        jQuery.cookie("listItemTitle", removed_item);

    });
});```

1 Ответ

0 голосов
/ 09 октября 2019

Это должно помочь:

$.cookie("test", 1, {
   expires : 10,           // Expires in 10 days

   path    : '/',          // The value of the path attribute of the cookie
                           // (Default: path of page that created the cookie).

   domain  : 'jquery.com', // The value of the domain attribute of the cookie
                           // (Default: domain of page that created the cookie).

   secure  : true          // If set to true the secure attribute of the cookie
                           // will be set and the cookie transmission will
                           // require a secure protocol (defaults to false).
});

Чтобы прочитать значение cookie:

var cookieValue = $.cookie("test");

Выможет потребоваться указать параметр пути, если cookie был создан по пути, отличному от текущего:

var cookieValue = $.cookie("test", { path: '/foo' }); Как мне установить / удалить cookie с помощью jQuery?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...