简体   繁体   中英

How do I pass in a cookie value returned from a javascript function to a JSON parameter field?

I have this kendo object and I'm concerned with this part of its configuration:

data: {
          awardTitleId: e.data.AwardTitleId,
          personId: X, //needs to be a variable
          nameId: Y //needs to be a variable
      }

I get the values for personId and nameId and store them into cookies.

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

The issue here is that for me to use the returned value from the "readCookie" function, it needs to be in a variable so I can do:

data: {
          awardTitleId: e.data.AwardTitleId,
          personId: variable1,
          nameId: variable2
      }

I can't do this:

data: {
          awardTitleId: e.data.AwardTitleId,
          personId: readCookie("personId"),
          nameId: readCookie("nameId")
      }

So my question is, how do I USE the values returned by these java script functions in my code? They sort of have to be "global variables" so that I can use it in other parts/events of the web page.

I tried declaring these variables at the top of my page, outside all functions but I keep getting 0's for the Ids.

The cookie functions ARE working, btw.

EDIT -

The function IS returning a value:

It looks like you're using jQuery so if you have a ready function you could set these values into your data object like this

var data: {
      awardTitleId: e.data.AwardTitleId, //wherever you get this from
      personId: null,
      nameId: null
  }

$(function(){
    data.personId = readCookie("personId");
    data.nameId = readCookie("nameId");
});

I'm not sure where your data object exactly lives, hopefully not at the global scope but you mention needing that globally earlier so that's where I've left it.

By assigning the personId and nameId in the ready function of the page then you will have them for the life of the page and won't need to continually get them from a cookie.

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