[英]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: 我有这个kendo对象,我担心它的配置这一部分:
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. 我获得personId和nameId的值,并将它们存储到cookie中。
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: 这里的问题是,对于我来说,要使用“ readCookie”函数返回的值,它必须位于变量中,这样我才能执行以下操作:
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? 所以我的问题是,如何在代码中使用这些Java脚本函数返回的值? 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. 我尝试在所有功能之外的页面顶部声明这些变量,但我的ID始终为0。
The cookie functions ARE working, btw. 顺便说一句,cookie函数正在起作用。
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 看来您使用的是jQuery,因此,如果您有就绪的函数,可以将这些值设置为数据对象,如下所示
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. 通过在页面的ready函数中分配
personId
和nameId
,您将在页面的整个生命周期内拥有它们,而无需不断地从cookie中获取它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.