简体   繁体   English

如何使用 JavaScript 创建会话?

[英]How to create a session using JavaScript?

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.我使用 AJAX 请求 XML。 XML response I want to store in session and this session I want to pass to the server page(.asp).我想在会话中存储 XML 响应,而这个会话我想传递给服务器页面 (.asp)。 I mean to write something like:我的意思是写一些类似的东西:

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

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.如果是来自服务器的会话 ID,则服务器可以生成此 cookie。 And when another request is sent to the server the cookie will come too.当另一个请求发送到服务器时,cookie 也会出现。 Without having to do anything in the browser.无需在浏览器中执行任何操作。

However if it is javascript that creates the session Id.但是,如果它是创建会话 ID 的 javascript。 You can create a cookie with javascript, with a function like:您可以使用 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')

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.编辑:@Naveen 下面的评论是正确的。 You can use session storage instead.您可以改用会话存储。 ( https://www.w3schools.com/jsref/prop_win_sessionstorage.asp ) Thanks. https://www.w3schools.com/jsref/prop_win_sessionstorage.asp )谢谢。

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

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

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?是否无法直接通过 javascript 分配会话值? No, there is a way to do that.不,有办法做到这一点。

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?会话“controlID”已经创建,但是会话的值呢? is that persistent or can changeable via javascript?这是持久的还是可以通过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".会话已创建,但会话内部的值将是“'+ ​​strTest +'”而不是“这是我的会话”。 If you try to write variable directly into server code like:如果您尝试将变量直接写入服务器代码,例如:

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

Then an error will occur in you page "There is no parameter strTest in current context...".然后在您的页面中会出现错误“当前上下文中没有参数 strTest...”。 Until now it is still seem impossible to assign session values directly through javascript.直到现在,通过 javascript 直接分配会话值似乎仍然是不可能的。

Now I move to a new way.现在我转向一种新的方式。 Using WebMethod at code behind to do that.在后面的代码中使用 WebMethod 来做到这一点。 Look again your code with a little bit change:再次查看您的代码,稍作更改:

<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.在调用 web 方法从 javascript 创建会话之后。 The session "controlID" will has value "This is my session".会话“controlID”将具有值“这是我的会话”。

If you use the way I have explained, then please add this block of code inside form tag of your aspx page.如果您使用我解释的方式,那么请在您的 aspx 页面的表单标记中添加此代码块。 The code help to enable page methods.该代码有助于启用页面方法。

<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

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.我建议您重新阅读会话的定义。

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");

You can use sessionStorage it is similar to localStorage but sessionStorage gets clear when the page session ends while localStorage has no expiration set.您可以使用sessionStorage它与 localStorage 类似,但是 sessionStorage 在页面会话结束时清除,而 localStorage 没有设置过期时间。

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

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=/";
}

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.如果是来自服务器的会话 ID,则服务器可以生成此 cookie。 And when another request is sent to the server the cookie will come too.当另一个请求发送到服务器时,cookie 也会出现。 Without having to do anything in the browser.无需在浏览器中执行任何操作。

However if it is javascript that creates the session Id.但是,如果它是创建会话 ID 的 javascript。 You can create a cookie with javascript, with a function like:您可以使用 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 中的页面创建的,还是从服务器创建的。

You can use the name attr:您可以使用name attr:

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

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/1901857 for more information.有关更多信息,请参阅https://stackoverflow.com/a/532660/1901857

localStorage and jstorage are your best bets. localStorage和jstorage是您最好的选择。 localStorage is built in and jstorage offers lots of functionalites localStorage内置, jstorage提供许多功能

See localStorage browser support on caniuse . 请参阅caniuse上的localStorage浏览器支持

<script type="text/javascript">
function myfunction()
{
    var IDSes= "10200";
    '<%Session["IDDiv"] = "' + $(this).attr('id') + '"; %>'
    '<%Session["IDSes"] = "' + IDSes+ '"; %>';
     alert('<%=Session["IDSes"] %>');
}
</script>

link 关联

这是我所做的并且它起作用了,在 PHP 中创建了一个会话,并使用 xmlhhtprequest 来检查每次加载 HTML 页面时是否设置了会话,并且它适用于 Cordova。

Use HTML5 Local Storage.使用 HTML5 本地存储。 you can store and use the data anytime you please.您可以随时存储和使用数据。

<script>
    // Store
    localStorage.setItem("lastname", "Smith");

    // Retrieve
    var data = localStorage.getItem("lastname");

</script>

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

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