jQuery 在 JavaScript 中获取当前会话值?

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

Get Current Session Value in JavaScript?

jqueryasp.netsession

提问by SparAby

I have a scenario where I open my web application in a browser but in two separate tabs.

我有一个场景,我在浏览器中打开我的 Web 应用程序,但在两个单独的选项卡中。

In one tab I signed out from the application and as a result the all session values becomes null. While in the other tab I clicked on an anchor tag in the webapplication. In the anchor tag's jquery-on click event I have checked the session value. Here I am supposed to get the session as null(since I logged out the application from the other tab), but I am getting session value as logged in user(probably because no page refresh occurs).

在一个选项卡中,我退出了应用程序,结果所有会话值都变为空。在另一个选项卡中,我单击了 web 应用程序中的锚标记。在锚标记的 jquery-on 单击事件中,我检查了会话值。在这里,我应该将会话设置为空(因为我从另一个选项卡中注销了应用程序),但是我以登录用户的身份获取了会话值(可能是因为没有发生页面刷新)。

My idea is to check the session on jQuery and if the session is null make the application logout,otherwise show a popup page..

我的想法是检查 jQuery 上的会话,如果会话为空,则使应用程序注销,否则显示一个弹出页面..

Here's my code for getting the session value

这是我获取会话值的代码

$(".a".click(function(){
   var session=var data = '@Session["UserName"]';
   if(session!=null){
    //Show popup
   }
   else{
    //Show loginpage
   }

}))

How can I get the current session value in jQuery?

如何在 jQuery 中获取当前会话值?

回答by Stefano Altieri

The session is a server side thing, you cannot access it using jQuery. You can write an Http handler (that will share the sessionid if any) and return the value from there using $.ajax.

会话是服务器端的事情,您无法使用 jQuery 访问它。您可以编写一个 Http 处理程序(如果有的话,它将共享 sessionid)并使用$.ajax.

回答by Najib

Another approach is in your chtml

另一种方法是在你的 chtml

<input type="hidden" id="hdnSession" data-value="@Request.RequestContext.HttpContext.Session['someKey']" />

  and the script is

  脚本是

var sessionValue= $("#hdnSession").data('value');

or you may access directly by

或者您可以直接访问

 jQuery(document).ready(function ($) {
        var value = '@Request.RequestContext.HttpContext.Session["someKey"]';
    }); 

回答by SHEKHAR SHETE

Accessing & Assigning the Session Variable using Javascript:

使用 Javascript 访问和分配会话变量:

Assigning the ASP.NET Session Variable using Javascript:

使用 Javascript 分配 ASP.NET 会话变量:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

使用 Javascript 访问 ASP.NET Session 变量:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

Already Answered here

已经在这里回答

回答by SparAby

The way i resolved was, i have written a function in controller and accessed it via ajax on jquery click event

我解决的方法是,我在控制器中编写了一个函数,并在 jquery 单击事件上通过 ajax 访问它

First of all i want to thank @Stefano Altieri for giving me an idea of how to implement the above scenario,you are absolutely right we cannot access current session value from clientside when the session expires.

首先,我要感谢@Stefano Altieri 让我了解如何实现上述场景,您是绝对正确的,我们无法在会话到期时从客户端访问当前会话值。

Also i would like to say that proper reading of question will help us to answer the question carefully.

另外我想说,正确阅读问题将有助于我们仔细回答问题。

回答by Faradin

i tested this method and it worked for me. hope its useful.

我测试了这个方法,它对我有用。希望它有用。

assuming that you have a file named index.php
and when the user logs in, you store the username in a php session; ex. $_SESSION['username'];

假设您有一个名为 index.js 的文件。php
,当用户登录时,您将用户名存储在 php 会话中;前任。$_SESSION['用户名'];

you can do something like this in you index.php file

你可以在你的 index.php 文件中做这样的事情

<script type='text/javascript'>
  var userName = "<?php echo $_SESSION['username'] ?>"; //dont forget to place the PHP code block inside the quotation 
</script>

now you can access the variable userIdin another script block placed in the index.php file, or even in a .js file linked to the index.php

现在您可以在 index.php 文件中的另一个脚本块中访问变量userId,甚至可以在链接到 index.php 的 .js 文件中访问

ex. in the index.js file

前任。在 index.js 文件中

$(document).ready(function(){
    alert(userId);   
})

it could be very useful, since it enables us to use the username and other user data stoerd as cookies in ajax queries, for updating database tables and such.

它可能非常有用,因为它使我们能够在 ajax 查询中使用用户名和其他用户数据作为 cookie,用于更新数据库表等。

if you dont want to use a javascript variable to contain the info, you can use an input with "type='hidden';

如果您不想使用 javascript 变量来包含信息,您可以使用带有 "type='hidden'; 的输入;

ex. in your index.php file, write:

前任。在你的 index.php 文件中,写:

<?php echo "<input type='hidden' id='username' value='".$_SESSION['username']."'/>";
?>

however, this way the user can see the hidden input if they ask the browser to show the source code of the page. in the source view, the hidden input is visible with its content. you may find that undesireble.

但是,如果用户要求浏览器显示页面的源代码,则用户可以通过这种方式看到隐藏的输入。在源视图中,隐藏的输入及其内容可见。你可能会觉得这是不受欢迎的。

回答by Mubarak

I am using C# mvc Application. I have created a session in the Controller class like this

我正在使用 C# mvc 应用程序。我在 Controller 类中创建了一个这样的会话

string description = accessDB.LookupSomeString(key, ImpDate);
this.Session["description"] = description;    

in the View, We access the session value and store it in a variable, like this (this is within an $.ajax, but I think it should work within any jquery)

在视图中,我们访问会话值并将其存储在一个变量中,就像这样(这是在 $.ajax 中,但我认为它应该在任何 jquery 中工作)

var Sessiondescription = '@Session["description"]';
alert(Sessiondescription);

回答by George H

would be a lot easier to use Razor code in your page.

在页面中使用 Razor 代码会容易得多。

in my example, i needed to set a hidden field with a session variable.

在我的示例中,我需要使用会话变量设置一个隐藏字段。

$('#clearFormButton').click(function(){
    ResetForm();
    $('#hiddenJobId').val(@Session["jobid"]);
});

that easy. remember, you need to preface the Session with a @ sign for razor syntax.

这么简单。请记住,您需要在 Session 前面加上一个 @ 符号来表示 razor 语法。

回答by Pankaj Kumar

<script type="text/javascript">
$(document).ready(function(){

   var userId=<%: Session["userId"] %>;
    alert(userId);   
})   
</script>
**Get the current session value in jQuery**

回答by Vlog -the-world

this is how i used ->

这就是我使用的方式->

<body  onkeypress='myFunction(event)'>

<input type='hidden' id='homepage' value='$_SESSION[homepage]'>


<script>
    function myFunction(event){var x = event.which;if(x == 13){var homepage 
    =document.getElementById('homepage').value;
    window.location.href=homepage;}else{     
    document.getElementById("h1").innerHTML = "<h1> Press <i> ENTER </i> to go back... </h1>";}}
</script>
</body>

回答by Vinay Pratap Singh

try like this

像这样尝试

var username= "<%= Session["UserName"]%>";