如何使用 JavaScript 创建会话?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2257631/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:30:25  来源:igfitidea点击:

How to create a session using JavaScript?

javascriptasp.netsession

提问by Alex

How to create session in JavaScript?

如何在 中创建会话JavaScript

I try like this:

我像这样尝试:

<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script> 

Why I looking for session?

为什么我要找会话?

I make a request for XML using AJAX. XML response I want to store in session and this session I want to pass to the server page(.asp). I mean to write something like:

我使用 AJAX 请求 XML。我想在会话中存储 XML 响应,而这个会话我想传递给服务器页面 (.asp)。我的意思是写一些类似的东西:

<% response.write session("MySession")%>

回答by Mic

You can store and read string information in a cookie.

您可以在 cookie 中存储和读取字符串信息。

If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.

如果是来自服务器的会话 ID,则服务器可以生成此 cookie。当另一个请求发送到服务器时,cookie 也会出现。无需在浏览器中执行任何操作。

However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:

但是,如果它是创建会话 ID 的 javascript。您可以使用 javascript 创建一个 cookie,其函数如下:

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

Then in each page you need this session Id you can read the cookie, with a function like:

然后在您需要此会话 ID 的每个页面中,您可以读取 cookie,其功能如下:

function readCookie(name) {
    var i, c, ca, nameEQ = name + "=";
    ca = document.cookie.split(';');
    for(i=0;i < ca.length;i++) {
        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 '';
}

The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.

读取函数可以在编写它的同一域的任何页面或选项卡上工作,无论 cookie 是从 javascript 中的页面创建的,还是从服务器创建的。

To store the id:

要存储 ID:

var sId = 's234543245';
writeCookie('sessionId', sId, 3);

To read the id:

要读取 ID:

var sId = readCookie('sessionId')

回答by Tri Nguyen Dung

I assume you are using ASP.NET MVC (C#), if not then this answer is not in your issue.

我假设您使用的是 ASP.NET MVC (C#),如果不是,那么这个答案不在您的问题中。

Is it impossible to assign session values directly through javascript? No, there is a way to do that.

是否无法直接通过 javascript 分配会话值?不,有办法做到这一点。

Look again your code:

再看看你的代码:

<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script> 

A little bit change:

一点点变化:

<script type="text/javascript" >
{
  <%Session["controlID"] = "This is my session";%>
}
</script>

The session "controlID" has created, but what about the value of session? is that persistent or can changeable via javascript?

会话“controlID”已经创建,但是会话的值呢?这是持久的还是可以通过javascript改变的?

Let change a little bit more:

让我们再改变一点:

<script type="text/javascript" >
{
  var strTest = "This is my session"; 
  <%Session["controlID"] = "'+ strTest +'";%>
}
</script>

The session is created, but the value inside of session will be "'+ strTest +'" but not "This is my session". If you try to write variable directly into server code like:

会话已创建,但会话内部的值将是“'+ ​​strTest +'”而不是“这是我的会话”。如果您尝试将变量直接写入服务器代码,例如:

<%Session["controlID"] = strTest;%>

Then an error will occur in you page "There is no parameter strTest in current context...". Until now it is still seem impossible to assign session values directly through javascript.

然后在您的页面中会出现错误“当前上下文中没有参数 strTest...”。直到现在,通过 javascript 直接分配会话值似乎仍然是不可能的。

Now I move to a new way. Using WebMethod at code behind to do that. Look again your code with a little bit change:

现在我转向一种新的方式。在后面的代码中使用 WebMethod 来做到这一点。再次查看您的代码,稍作更改:

<script type="text/javascript" >
{
 var strTest = "This is my session"; 
 PageMethods.CreateSessionViaJavascript(strTest);
}
</script> 

In code-behind page. I create a WebMethod:

在代码隐藏页面中。我创建了一个 WebMethod:

[System.Web.Services.WebMethod]
public static string CreateSessionViaJavascript(string strTest)
{
    Page objp = new Page();
    objp.Session["controlID"] = strTest; 
    return strTest;
}

After call the web method to create a session from javascript. The session "controlID" will has value "This is my session".

在调用 web 方法从 javascript 创建会话之后。会话“controlID”将具有值“这是我的会话”。

If you use the way I have explained, then please add this block of code inside form tag of your aspx page. The code help to enable page methods.

如果您使用我解释的方式,那么请在您的 aspx 页面的表单标签中添加此代码块。该代码有助于启用页面方法。

<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>

Source: JavaScript - How to Set values to Session in Javascript

来源:JavaScript - 如何在 Javascript 中为会话设置值

Happy codding, Tri

快乐编码,Tri

回答by Rafael M.

You can use Local storage.

您可以使用本地存储。

local storage is same as session. the data will be removed when you close the browser.

本地存储与会话相同。当您关闭浏览器时,数据将被删除。

<script> 
localStorage.setItem('lastname','Smith');

alert(localStorage.getItem('lastname'));
</script>

Edit: @Naveen comment below is correct. You can use session storage instead. (https://www.w3schools.com/jsref/prop_win_sessionstorage.asp) Thanks.

编辑:@Naveen 下面的评论是正确的。您可以改用会话存储。(https://www.w3schools.com/jsref/prop_win_sessionstorage.asp)谢谢。

<script> 
sessionStorage.setItem('lastname','Smith');

alert(sessionStorage.getItem('lastname'));
</script>

回答by MindFold

I think you misunderstood the concept of session, session is a server side per-user-data-store which allows you to save user data on the server side.

我认为您误解了会话的概念,会话是服务器端每用户数据存储,它允许您在服务器端保存用户数据。

thus, you have 2 options, resort to use cookies, which will give the illusion of session(but not quite the same), you can access cookies very simply by document.cookie .

因此,您有 2 个选择,使用 cookie,这会产生会话的错觉(但不完全相同),您可以通过 document.cookie 非常简单地访问 cookie。

but, if you want your server be aware of the session, you need to use some sort of server request probably the best way is to use AJAX to do this.

但是,如果您希望服务器知道会话,则需要使用某种服务器请求,最好的方法可能是使用 AJAX 来执行此操作。

I would recommend you to re-read the definition of sessions.

我建议您重新阅读会话的定义。

回答by Jibin Mathew

You can try jstorage javascript plugin, it is an elegant way to maintain sessions check this http://www.jstorage.info/

您可以尝试 jstorage javascript 插件,这是一种保持会话的优雅方式,请查看http://www.jstorage.info/

include the jStorage.js script into your html

将 jStorage.js 脚本包含到您的 html 中

<script src="jStorage.js"></script>

Then in your javascript place the sessiontoken into the a key like this

然后在您的 javascript 中将 sessiontoken 放入这样的 a 键中

$.jStorage.set("YOUR_KEY",session_id);

Where "YOUR_KEY" is the key using which you can access you session_id , like this:

其中“YOUR_KEY”是您可以访问 session_id 的密钥,如下所示:

var id = $.jStorage.get("YOUR_KEY");

回答by Rim Gazzah

You can use sessionStorageit is similar to localStorage but sessionStorage gets clear when the page session ends while localStorage has no expiration set.

See https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

您可以使用sessionStorage它与 localStorage 类似,但是 sessionStorage 在页面会话结束时清除,而 localStorage 没有设置过期时间。

请参阅https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

回答by gaurav

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

回答by Itay Moav -Malimovka

You can use the nameattr:

您可以使用nameattr:

<script type="text/javascript" >
{
window.name ="This is my session";
}
</script> 

You still have to develop for yourself the format to use, or use a wrapper from an already existing library (mootools, Dojo etc).
You can also use cookies, but they are more heavy on performance, as they go back and forth from the client to the server, and are specific to one domain.

您仍然需要为自己开发要使用的格式,或者使用来自现有库(mootools、Dojo 等)的包装器。
您也可以使用 cookie,但它们对性能的影响更大,因为它们在客户端和服务器之间来回传递,并且特定于一个域。

回答by mst

If you create a cookie and do not specify an expiration date, it will create a session cookie which will expire at the end of the session.

如果您创建 cookie 并且未指定到期日期,它将创建一个会话 cookie,该 cookie 将在会话结束时到期。

See https://stackoverflow.com/a/532660/1901857for more information.

有关更多信息,请参阅https://stackoverflow.com/a/532660/1901857

回答by Best Dude

You can store and read string information in a cookie.

您可以在 cookie 中存储和读取字符串信息。

If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.

如果是来自服务器的会话 ID,则服务器可以生成此 cookie。当另一个请求发送到服务器时,cookie 也会出现。无需在浏览器中执行任何操作。

However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:

但是,如果它是创建会话 ID 的 javascript。您可以使用 javascript 创建一个 cookie,其函数如下:

The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.

读取函数可以在编写它的同一域的任何页面或选项卡上工作,无论 cookie 是从 javascript 中的页面创建的,还是从服务器创建的。