简体   繁体   English

如何使用JavaScript为会话分配值

[英]How To Assign Value To Session Using Javascript

Work on Asp.Net C# VS08 I would like to assign a value to Session using javascript. 在Asp.Net C#VS08上工作我想使用javascript为Session分配一个值。 Is it possible? 可能吗?

example: Session["Id"] = document.getElementById("id").value; 例如:Session [“ Id”] = document.getElementById(“ id”)。value;

The session is a server-side concept; 会话是服务器端的概念; Javascript has no conception of it. Javascript没有概念。

You can make an AJAX service that sets a session value. 您可以进行设置会话值的AJAX服务。

However, you should probably use a cookie instead. 但是,您可能应该改用cookie。
You can set cookies in Javascript using this library , among others. 您可以使用此库等在Javascript中设置cookie。

No it is not possible to do that directly with JavaScript on the client-side. 不,不可能直接在客户端使用JavaScript做到这一点。

Sessions are handled on the server-side. 会话在服务器端处理。 In general your browser would simply store a cookie which uniquely identifies a session stored on your server. 通常,您的浏览器将只存储一个cookie,该cookie唯一标识存储在您服务器上的会话。 When you change the value of a session variable, you are storing this on the server, and the browser cookie would be unaffected. 当您更改会话变量的值时,会将其存储在服务器上,并且浏览器cookie不会受到影响。

You could however use JavaScript to send an XMLHttpRequest to your ASP.NET application, which in turn changes the session variable on the server-side. 但是,您可以使用JavaScript将XMLHttpRequest发送到ASP.NET应用程序,从而在服务器端更改会话变量。 Since this involves a round-trip to the server, you would have to wait for the response, to confirm that the operation succeeded. 由于这涉及到服务器的往返,因此您必须等待响应,以确认操作成功。

Assigning to a session variable like this isn't possible in JavaScript. 在JavaScript中无法像这样分配会话变量。 Best you can do is write data to a cookie. 最好的办法是将数据写入Cookie。

http://www.w3schools.com/js/js_cookies.asp http://www.w3schools.com/js/js_cookies.asp

Otherwise if you want to communicate to the server use Ajax. 否则,如果要与服务器通信,请使用Ajax。

No it is not possible. 不,这是不可能的。 Session is server side object. 会话是服务器端对象。 A couple of ways to do that would be to send cookies from JavaScript and use them on the server side to assign a value to a session variable, or to make an AJAX call and set the values on the backend. 这样做的几种方法是从JavaScript发送cookie并在服务器端使用它们为会话变量分配值,或者进行AJAX调用并在后端设置值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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