猿问

如何访问会话变量并在javascript中进行设置?

在后台代码中,我设置Session了一些数据。


Session["usedData"] = "sample data";

问题是如何在javascript中获取会话值(在我的示例中为“示例数据”)并设置Session["usedData"]新值?


RISEBY
浏览 608回答 3
3回答

临摹微笑

您不能Session直接在JavaScript中访问。您可以创建一个隐藏字段并将其传递到页面,然后使用JavaScript通过以下方式检索对象 document.getElementById

慕侠2389804

Javascript无法直接设置会话值。为了从javascript设置会话值,我按以下方式进行ajax调用。在线查询在ASPx文件或html中,&nbsp;<script type="text/javascript">&nbsp;$(function(){&nbsp; &nbsp;//Getting values from session and saving in javascript variable.&nbsp; &nbsp;// But this will be executed only at document.ready.&nbsp; &nbsp;var firstName = '<%= Session["FirstName"] ?? "" %>';&nbsp; &nbsp;var lastName = '<%= Session["LastName"] ?? "" %>';&nbsp; &nbsp;$("#FirstName").val(firstName);&nbsp; &nbsp;$("#LastName").val(lastName);&nbsp; &nbsp;$('Button').click(function(){&nbsp; &nbsp; &nbsp;//Posting values to save in session&nbsp; &nbsp; &nbsp;$.post(document.URL+'?mode=ajax',&nbsp;&nbsp; &nbsp; &nbsp;{'FirstName':$("#FirstName").val(),&nbsp; &nbsp; &nbsp;'LastName':$("#LastName").val()&nbsp; &nbsp; &nbsp;} );&nbsp; &nbsp;});&nbsp;});在服务器端,protected void Page_Load(object sender, EventArgs e)&nbsp;{&nbsp; &nbsp; &nbsp; if(Request.QueryString["mode"] != null && Request.QueryString["mode"] == "ajax")&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Saving the variables in session. Variables are posted by ajax.&nbsp; &nbsp; &nbsp; &nbsp; Session["FirstName"] = Request.Form["FirstName"] ?? "";&nbsp; &nbsp; &nbsp; &nbsp; Session["LastName"] = Request.Form["LastName"] ?? "";&nbsp; &nbsp; &nbsp; }&nbsp;}如Shekhar和Rajeev所言,获取会话值var firstName = '<%= Session["FirstName"] ?? "" %>';希望这可以帮助。
随时随地看视频慕课网APP
我要回答