如何使用JavaScript创建会话? [英] How to create a session using JavaScript?

查看:162
本文介绍了如何使用JavaScript创建会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 JavaScript中创建会话

我尝试这样:

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

为什么我要寻找会话?

Why I looking for session?

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

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:

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


推荐答案

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

You can store and read string information in a cookie.

如果是来自服务器的会话ID,服务器可以生成此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.

但是,如果是javascript,则会创建会话ID。您可以使用javascript创建一个cookie,其功能如下:

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

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

然后在每个页面中你需要这个会话ID你可以读取cookie,一个函数,如:

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

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 '';
}

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

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.

存储id:

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

阅读ID:

var sId = readCookie('sessionId')

这篇关于如何使用JavaScript创建会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆