JSP - 如何在 session.setAttribute 中传递 javascript var?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32884887/
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
JSP - how to pass a javascript var in session.setAttribute?
提问by Tom
New to learning JSP, and trying out passing data between two pages.
刚开始学习 JSP,并尝试在两个页面之间传递数据。
I'm wondering if it is possible to pass a javascript variable to session.setAttribute()
我想知道是否可以将 javascript 变量传递给 session.setAttribute()
At the moment, I can pass a string of text through 2 jsp files like so:
目前,我可以通过 2 个 jsp 文件传递一串文本,如下所示:
JSP1:
JSP1:
<% String text = "hello";
session.setAttribute("test", text);%>
JSP2:
JSP2:
var someText = "<%=session.getAttribute("test")%>"
which works fine.
这工作正常。
However, is it possible to pass through a var
into session.setAttribute
instead? I store some data in a javascript variable and would like to send it across to the second JSP file.
但是,是否可以通过var
intosession.setAttribute
代替?我将一些数据存储在一个 javascript 变量中,并希望将其发送到第二个 JSP 文件。
So for example:
例如:
var number = 7;
<%session.setAttribute("test", number);%>
I've tried this out and I get the error "number cannot be resolved to a variable"
我试过了,我收到错误“数字无法解析为变量”
Thanks!
谢谢!
采纳答案by Harshit Shrivastava
You cannot do that since javascript executes on client & JSP executes on server side.
您不能这样做,因为 javascript 在客户端执行而 JSP 在服务器端执行。
If you want to set javascript variable to JSP session, then you pass this variable through the URL like this
如果要将 javascript 变量设置为 JSP 会话,则可以像这样通过 URL 传递此变量
var number = 7;
window.location="http://example.com/index.jsp?param="+number;
Now receive this var in your JSP page like this
现在像这样在你的 JSP 页面中接收这个变量
String var = request.getParameter("param");
Now set it in session
现在在会话中设置它
session.setAttribute("test", var);
EDIT :
编辑 :
var number = 7;
<%session.setAttribute("test", number);%>
In the above code, server will only execute the code inside <% %>. It does not know anything outside of the JSP tags. So, it will also dont know about your javascript variable number
.
上面的代码中,server只会执行<%%>里面的代码。它不知道 JSP 标记之外的任何内容。因此,它也不知道您的 javascript 变量number
。
Server executes the code & the result will be sent to the browser, then your browser will execute that javascript code var number=7;
.
服务器执行代码 & 结果将发送到浏览器,然后您的浏览器将执行该 javascript 代码var number=7;
。
Hope, now it is clear for you.
希望,现在你很清楚了。