在 javascript 代码中读取 jstl 变量。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24559149/
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
Reading a jstl variable in javascript code.
提问by webExplorer
I want to read a jstl variable in a javascript function.
我想在 javascript 函数中读取 jstl 变量。
JS code submits a form.
JS代码提交表单。
$("#userSubmit").on('submit', function () {
document.getElementById("userForm").submit();
});
So in server code -
所以在服务器代码中 -
request.setAttribute("userId", 435);
and after the page is loaded -> in the javascript code -
页面加载后 -> 在 javascript 代码中 -
$("#textBoxInp").keyup(function() {
// I want to access the userId here.
// in html code i can acccess it using JSTL syntax ${userId}
});
采纳答案by Luiggi Mendoza
Just write the Expression Language directly in your JavaScript code:
只需直接在您的 JavaScript 代码中编写表达式语言:
$("#textBoxInp").keyup(function() {
var userId = '${userId}';
});
Note that this won't work if the JavaScript code is placed in a external file and is invoked in the JSP. In this case, you may refer to one of the four ways that BalusC explain here: Mixing JSF EL in a Javascript file(he explains five, but one of them is JSF specific).
请注意,如果 JavaScript 代码放置在外部文件中并在 JSP 中调用,这将不起作用。在这种情况下,您可以参考 BalusC 在这里解释的四种方式之一:在 Javascript 文件中混合 JSF EL(他解释了五种,但其中一种是特定于 JSF 的)。
回答by user3657302
One way is as suggested by Mendoza, but it will not work in case of having separate Javascript file.
一种方法是 Mendoza 建议的,但如果有单独的 Javascript 文件,它就不起作用。
in that case, another way is adding hidden field in JSP page, and reading same from Javascript.
在这种情况下,另一种方法是在 JSP 页面中添加隐藏字段,并从 Javascript 中读取相同内容。
JSP code:
JSP代码:
<input type="hidden" id="xID" name="x" value="${myAttribute}">
JS code:
JS代码:
var myAtt = document.getElementById("xID").value;
回答by Anil Jain
totalClients is jstl variable and to read in javascript block please see below
totalClients 是 jstl 变量,要在 javascript 块中读取,请参见下文
<script type="text/javascript">
$(document).ready(function() {
var tc = "<c:out value='${totalClients}'/>";
});
回答by swethaesp
If you want to access jstl variable in a javascript script function, you won't be able to access them directly. Here's a roundabout way(easy to implement) to do it.
如果您想在 javascript 脚本函数中访问 jstl 变量,您将无法直接访问它们。这是一种迂回的方式(易于实施)来做到这一点。
In the HTML code have a paragraph with the required variable.
<p id = "var" disabled = "disabled">${variable}</p>
Access the variable using
.innerHTML
inside the JavaScript function.function myFunction() { ... var jstl_var = document.getElementById("var").innerHTML; ... }
在 HTML 代码中有一个带有所需变量的段落。
<p id = "var" disabled = "disabled">${variable}</p>
使用
.innerHTML
JavaScript 函数内部访问变量。function myFunction() { ... var jstl_var = document.getElementById("var").innerHTML; ... }