如何将 Javascript 变量传递给 <jsp:setProperty> 和 JSTL?

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

How do I pass Javascript variable to <jsp:setProperty> and JSTL?

javascriptjspjstl

提问by Tony

How do I pass Javascript variable to and JSTL?

如何将 Javascript 变量传递给 JSTL?

<script>

    var name = "john";  

    <jsp:setProperty name="emp" property="firstName" value=" "/>   // How do I set javascript variable(name) value here ?

    <c:set var="firstName" value=""/>  // How do I set javascript variable (name) value here ?     

  </script>

回答by BalusC

You need to send it as a request parameter. One of the ways is populating a hidden input field.

您需要将其作为请求参数发送。其中一种方法是填充隐藏的输入字段。

<script>document.getElementById('firstName').value = 'john';</script>
<input type="hidden" id="firstName" name="firstName">

This way you can get it in the server side as request parameter when the form is been submitted.

通过这种方式,您可以在提交表单时在服务器端获取它作为请求参数。

<jsp:setProperty name="emp" property="firstName" value="${param.firstName}" />

An alternative way is using Ajax, but that's a completely new story/answer at its own.

另一种方法是使用 Ajax,但这本身就是一个全新的故事/答案。

See also:

也可以看看:

If you can't seem to find your previously asked questions back, head to your user profile!

如果您似乎无法找回您之前提出的问题,请前往您的用户资料

回答by Stian

AFAIK you can't send data from JavaScript to JSTL that way. Because the JSTL tags are handled serverside, so the <jsp:>tags will be parsed on the server and replaced by HTML. So the <jsp:>tags won't be a part of the response that is sent back to the client; it will consist only of HTML/text. Therefore you can't access the <jsp:>tags from JavaScript, because they won't exist in the document.

AFAIK 你不能以这种方式从 JavaScript 发送数据到 JSTL。因为 JSTL 标签是在服务器端处理的,所以这些<jsp:>标签会在服务器上被解析并被 HTML 替换。所以<jsp:>标签不会成为发送回客户端的响应的一部分;它将仅包含 HTML/文本。因此您无法<jsp:>从 JavaScript访问标签,因为它们不会存在于文档中。

Edit: sorry, the <jsp:>tags wasn't visible.

编辑:抱歉,<jsp:>标签不可见。

回答by Russ

<script>
var name = "<jsp:getProperty name="emp" property="firstName" />";
</script>

The JSP code executes before the JavaScript so by the time the JavaScript gets processed the tag will be replaced with the contents of emp.firstName.

JSP 代码在 JavaScript 之前执行,因此在处理 JavaScript 时,标记将替换为 emp.firstName 的内容。