How To Assign Value To Session Using Javascript

2020-07-23 08:37发布

Work on Asp.Net C# VS08 I would like to assign a value to Session using javascript. Is it possible?

example: Session["Id"] = document.getElementById("id").value;

标签: javascript
4条回答
beautiful°
2楼-- · 2020-07-23 09:06

Assigning to a session variable like this isn't possible in JavaScript. Best you can do is write data to a cookie.

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

Otherwise if you want to communicate to the server use Ajax.

查看更多
贼婆χ
3楼-- · 2020-07-23 09:12

No it is not possible to do that directly with JavaScript on the client-side.

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. When you change the value of a session variable, you are storing this on the server, and the browser cookie would be unaffected.

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. Since this involves a round-trip to the server, you would have to wait for the response, to confirm that the operation succeeded.

查看更多
地球回转人心会变
4楼-- · 2020-07-23 09:29

The session is a server-side concept; Javascript has no conception of it.

You can make an AJAX service that sets a session value.

However, you should probably use a cookie instead.
You can set cookies in Javascript using this library, among others.

查看更多
冷血范
5楼-- · 2020-07-23 09:29

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.

查看更多
登录 后发表回答