javascript - чтение значения cookie, триггерная функция, если часть строки = - PullRequest
0 голосов
/ 19 октября 2011

У меня есть файл cookie -

LLBVAT

, и строка в файле cookie (которая может измениться, но структура останется прежней):

Итак, язнаю, что мне нужно прочитать cookie, а затем запустить функцию для возвращаемой строки.

A0A64A06500000B754E9DD10B1381:0:false:false:99:9999:99:false:0:-1:0:0:0:EMAILPCD:1319094000000:82

Мне нужно вызвать функцию для второго ложного (4-е значение).

Любая помощь будет оценена.спасибо.

Можно ли использовать меньше кода:

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;
}

Ответы [ 4 ]

3 голосов
/ 19 октября 2011

разделить значение на :

var trigger = "A0A64A06500000B754E9DD10B1381:0:false:false:99:9999:99:false:0:-1:0:0:0:EMAILPCD:1319094000000:82".split(':')[3] === "false";
if (trigger) func();

сравнение очень важно, поскольку if ("false") является правдивым

Получите печенье от https://developer.mozilla.org/en/DOM/document.cookie

docCookies = {
  getItem: function (sKey) {
    if (!sKey || !this.hasItem(sKey)) { return null; }
    return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
  },
  /**
  * docCookies.setItem(sKey, sValue, vEnd, sPath, sDomain, bSecure)
  *
  * @argument sKey (String): the name of the cookie;
  * @argument sValue (String): the value of the cookie;
  * @optional argument vEnd (Number, String, Date Object or null): the max-age in seconds (e.g., 31536e3 for a year) or the
  *  expires date in GMTString format or in Date Object format; if not specified it will expire at the end of session; 
  * @optional argument sPath (String or null): e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location;
  * @optional argument sDomain (String or null): e.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not
  * specified, defaults to the host portion of the current document location;
  * @optional argument bSecure (Boolean or null): cookie will be transmitted only over secure protocol as https;
  * @return undefined;
  **/
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
    var sExpires = "";
    if (vEnd) {
      switch (typeof vEnd) {
        case "number": sExpires = "; max-age=" + vEnd; break;
        case "string": sExpires = "; expires=" + vEnd; break;
        case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
      }
    }
    document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
  },
  removeItem: function (sKey) {
    if (!sKey || !this.hasItem(sKey)) { return; }
    var oExpDate = new Date();
    oExpDate.setDate(oExpDate.getDate() - 1);
    document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";
  },
  hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
};

// docCookies.setItem("test1", "Hello world!");
// docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
// docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
// docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");
// docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");
// docCookies.setItem("test6", "Hello world!", 150);
// docCookies.setItem("test7", "Hello world!", 245, "/content");
// docCookies.setItem("test8", "Hello world!", null, null, "example.com");
// docCookies.setItem("test9", "Hello world!", null, null, null, true);

// alert(docCookies.getItem("test1"));

Итак:

if (docCookies.getItem("LLBVAT").split(':')[3] === "false") triggerFunction();
0 голосов
/ 29 мая 2014

Небольшое обновление кода разработчиков Mozilla, упомянутого выше: document.cookie возвращает только файлы cookie, в которых домен и путь соответствуют текущему URL (из-за ограничений безопасности). Чтобы прочитать файлы cookie, созданные для другого пути, вы можете использовать следующий обходной путь:

  getItem: function (sKey, sPath, sDomain) {
if (!sKey) {
  return "";
 }
var allCookie;
if (!sDomain && !sPath) {
  allCookie = document.cookie;
} else {
  var iframe = document.createElement("IFRAME");
  iframe.setAttribute("src", (sDomain ? sDomain : "") + (sPath ? sPath : ""));
  document.documentElement.appendChild(iframe);
  allCookie = iframe.contentDocument.cookie;
  iframe.parentNode.removeChild(iframe);
  iframe = null;
}
var sValue = decodeURIComponent(allCookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
return sValue; 

},

0 голосов
/ 20 октября 2011

Вы можете использовать либо плагин jQuery, либо Plain Old Javascript для управления cookie .Оттуда, как уже говорили другие, передайте результат методу, который разбивает строку и вызывает другой в зависимости от условия.

jQuery(document).ready(function(){
    var cookieValue = jQuery.cookie("LLBVAT");
    var result = process(cookieValue);
    if(result)
    { //do stuff }
});

function process(cookie){
   var result = cookie.split(':')[3];    
   return result === "false";
}
0 голосов
/ 19 октября 2011

Вы можете использовать это

function getTheResult(){
  //you can get this value as parameter in this function
  var val="A0A64A06500000B754E9DD10B1381:0:false:false:99:9999:99:false:0:-1:0:0:0:EMAILPCD:1319094000000:82";    

  //this final result will be as below by splitting the string
  var theresult =val.split(':')[3];    

  return theresult; //this will return 'false'
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...