如何在 JavaScript 中设置会话变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7588854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you set a session variable in JavaScript?
提问by hyprsleepy
Can this be done with a PageMethods call? I need to save some variables in a control so that they can be used by a control on another page at a later time. Is there a way to do this via JavaScript?
这可以通过 PageMethods 调用来完成吗?我需要在控件中保存一些变量,以便稍后可以由另一个页面上的控件使用它们。有没有办法通过 JavaScript 做到这一点?
回答by zzzzBov
Sounds like you need cookies, localStorage, or sessionStorage.
回答by The Evil Greebo
You can use JS to change the values in a hidden field, and capture them on the postback, which personally I think preferable to cookie usage if the value is only needed for the life of the current session.
您可以使用 JS 更改隐藏字段中的值,并在回发时捕获它们,我个人认为如果该值仅在当前会话的生命周期中需要,那么这比使用 cookie 更可取。
回答by Stefan Steiger
It's a very bad idea to do this with PageMethods.
用 PageMethods 这样做是一个非常糟糕的主意。
You can add a generic handler (*.ashx) and then do a XMLhttpRequest to this URL, passing it parameters.
您可以添加一个通用处理程序 (*.ashx),然后对该 URL 执行 XMLhttpRequest,向其传递参数。
Note that the ashx handler needs to inherit from IRequiresSessionState, in order to access a session.
请注意,为了访问会话,ashx 处理程序需要从 IRequiresSessionState 继承。
You can also get a session value that way.
您也可以通过这种方式获得会话值。
Like this:
像这样:
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler , IRequiresSessionState
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string item = context.Request.QueryString["item"] ?? "";
string update = context.Request.QueryString["update"] ?? "";
switch (item)
{
case "A":
if (!string.IsNullOrEmpty(update))
context.Session["A"] = update
object a = context.Session["A"];
context.Response.Write(a != null ? (string) a : "none");
break;
case "B":
if (!string.IsNullOrEmpty(update))
context.Session["B"] = update
object b = context.Session["B"];
context.Response.Write(b != null ? (string) b : "none");
break;
}
}
public bool IsReusable
{
get { return false; }
}
}
See my post here for XMLhttpRequest: Why does this JavaScript code ignore the timeout?
有关 XMLhttpRequest 的信息,请参阅我在此处的帖子: 为什么此 JavaScript 代码会忽略超时?
You might want to add a parameter no_cache=TIME_IN_MILLISECONDS, in order to beat browser caching.
您可能想要添加参数 no_cache=TIME_IN_MILLISECONDS,以击败浏览器缓存。
回答by Dan
I like to do it the following way:
我喜欢这样做:
javascript:
javascript:
function SendData(data) {
var postbackarg = "@@@@@" + data;
__doPostBack("txtTest", postbackarg);
}
VB In Page_Load event:
VB In Page_Load 事件:
If Me.IsPostBack Then
Dim controlName As String = Request.Params.Get("__EVENTTARGET")
Dim args As String = Request.Params.Get("__EVENTARGUMENT")
ProcessUserInterfaceData(controlName, args)
If (controlName = "txtTest" AndAlso args.IndexOf("@@@@@") = 0) Then
args = args.Substring(5, args.Length - 5)
'args now = data from the UI
End If
End If
This started from an example I found somewhere else. I cannot find it.. The only purpose for the 5 '@' is to identify the postback as coming from SendData.
这从我在别处找到的一个例子开始。我找不到它.. 5 '@' 的唯一目的是将回发标识为来自 SendData。
回答by Vignesh Subramanian
Session variables cannot be set using Javascript
directly
But you can use the following code to set session variables in aspx page
会话变量不能Javascript
直接使用设置但是可以使用下面的代码在aspx页面中设置会话变量
<%Session["SESSION VARIABLE NAME"] ="SOME STRING"; %>
You can check the same variable using an alert in javascript
您可以使用 javascript 中的警报检查相同的变量
alert('<%=Session["SESSION VARIABLE NAME"] %>');
Yes session variable can be set using Pagemethods using the below way
是的,可以使用以下方式使用 Pagemethods 设置会话变量
declare the below code in aspx.cs page
在 aspx.cs 页面中声明以下代码
[WebMethod]
public static void functionname(string st)
{
Home h = new Home();
System.Web.HttpContext.Current.Session["SessionUserName"] = st;
h.strUserName = (string)System.Web.HttpContext.Current.Session["SessionUserName"];
}
and call the function using pagemethod in aspx
并在 aspx 中使用 pagemethod 调用该函数
PageMethods.functionname("HELLO");
this will set the session variable to HELLO
这会将会话变量设置为 HELLO
You can also make an ajax call to the webmethod if you dont want to use pagemethods.function!!
如果不想使用 pagemethods.function 也可以对 webmethod 进行 ajax 调用!!