简体   繁体   中英

How to get the Last Value from Cookie with 2 variables inside Using split() methode in javascript

I have cookie that consist of 2 variables. I want to get the value from the variable #2 (the last one) But I don´t know how to deal with that.

From PHP

I have set cookie like this :

 setcookie ('mysite'.$user_id,'user_id='. $user_id. '&msg_id='. $c_id, time() + $cookie_time);

What I'm trying to get is the value of msg_id

In javascript

var ca="mysite"+user_id;
    ca = new Array();
        ca = document.cookie.split(';');

        for (var w in ca)

        NmeVal  = new Array();
        NmeVal  = ca[w].split('=');

But how can I get just only the value of msg_id as I mentioned above?

UPDATE

I got it to work now by doing this:

var NmeVal  = new Array();

    NmeVal  = ca[w].split('=');

    var vl =unescape(NmeVal[1]);  

    var gala = vl.split('=');

    alert(gala[2]);

I get the only value I want:: it work in IE, FIrefox, Chrome

But why didn´t it work in Safari ?

UPDATE # FINAL Finally I found the solution jquery.cookie.js Only 3 lines work and the job is done !!!

Create - get - delete cookie like crazy and the plugin is not that big file like other packages.

And because of this plug in I start to use cookie like crazy now :)

You are better of storing information in cookies this way:

setcookie("user_id", $user_id);
setcookie("msg_id", $c_id);
// ...

Javascript function for getting the cookie value by giving a name:

var user_id = getCookie("user_id");

function getCookie(name) {
    var result = ""; 
    var myCookie = " " + document.cookie + ";";
    var searchName = " " + name + "=";
    var startOfCookie = myCookie.indexOf(searchName); 

    var endOfCookie; 
    if (startOfCookie != -1) {
        startOfCookie += searchName.length; 
        endOfCookie = myCookie.indexOf(";", startOfCookie); 
        result = unescape(myCookie.substring(startOfCookie, endOfCookie)); 
    }
    return result; 
}

When you are parsing a cookie, parse from the outside in.

One thing I found when parsing the cookie you posted was an additional space before 'mysite'. Using the console and logging the results of each step can help you find small issues like that.

  • Split first by ','
  • loop and split by '='
  • unescape value to the right of the '='
  • Then in your case, loop and split by '&'

This routine should work for you ([Fiddle][5]):

// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    };
}


function parseCookie(cookie) {
    var vals = cookie.split(',');
    var nameValue = {}, cur, mysite;

    for (var i = 0; i < vals.length; ++i) {
        cur = vals[i].split('=');
        nameValue[cur[0].trim()] = unescape(cur[1]);
    }

    mysite = nameValue.mysite.split('&');
    nameValue.mysite = {};
    for (i = 0; i < mysite.length; ++i) {
        cur = mysite[i].split('=');
        nameValue.mysite[cur[0].trim()] = cur[1];
    }

    return nameValue;
}

var cookie = "PHPSESSID=oleGInunYQIP7QSLpDUVR3, mysite=usr%3DChrome%26hash%3D594f803b380a41396ed63dca39503542";

console.log(JSON.stringify(parseCookie(cookie)));

Result:

{"PHPSESSID":"oleGInunYQIP7QSLpDUVR3","mysite":{"usr":"Chrome","hash":"594f803b380a41396ed63dca39503542"}}

You can retrieve any value you need by something like:

var usr = result.mysite.usr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM