将 Struts 2 属性传递给 javascript

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

passing Struts 2 property to javascript

javascriptjakarta-eestruts2

提问by Max_Salah

I write the following code in simulate.jsp , to receive some String "simulationInfos" from the Server:

我在模拟.jsp 中编写了以下代码,以从服务器接收一些字符串“simulationInfos”:

<s:property id="simulationInfos" value="simulationInfos" /><br/>

When simulate.jsp has been returned, I can see, that the String simulationInfos existing.

当返回simulate.jsp 时,我可以看到,存在字符串simulationInfos。

My Question is: How can I pass simulationsInfos to java script?

我的问题是:如何将模拟信息传递给 java 脚本?

I tried the following:

我尝试了以下方法:

<script type="text/javascript">
var data=document.getElementById("simulationInfos").value;
console.log("data is: ", data);

And with jQuery:
var data=$("#simulationInfos").val();
</script>

and I get the following Error in Firebug: Uncaught TypeError: Cannot read property 'value' of null

我在 Firebug 中收到以下错误:未捕获的类型错误:无法读取 null 的属性“值”

How can I pass some struts 2 variable to javascript?

如何将一些 struts 2 变量传递给 javascript?

回答by jddsantaella

First, you should take a look to the HTML code that the JSP is generating. It can explain why you cannot retrieve the value. Then, maybe you will see that you need some extra HTML code. For example:

首先,您应该查看 JSP 生成的 HTML 代码。它可以解释为什么您无法检索该值。然后,也许您会发现您需要一些额外的 HTML 代码。例如:

<span id="simulationInfos"><s:property value="simulationInfos" /></span>

And in you script:

在你的脚本中:

alert("data is: " + simulationInfos.innerHTML);

If you take a look to the property tag doc, you can see that there is not any "id" parameter.

如果您查看属性标记doc,您会发现没有任何“id”参数。

Edition: JS correction.

版本:JS更正。

回答by Adam Shiemke

It looks like your id is simulationInfos but you are looking for simulateInfos in your js code. Since your getElementById is not returning anything, there is no value on a (null) return type.

看起来您的 id 是 simulationInfos,但您正在 js 代码中寻找simulateInfos。由于您的 getElementById 没有返回任何内容,因此(空)返回类型没有值。

Also, in console.log, use a + to concatenate your strings, not a comma.

此外,在 console.log 中,使用 + 连接字符串,而不是逗号。

回答by duckhunt

If you do not want to display property values use s:hidden tag like this:

如果您不想显示属性值,请使用 s:hidden 标记,如下所示:

<s:hidden id="simulationInfos" value="%{simulationInfos}" name="simulationInfos"/>

<script type="text/javascript">
var data=$("simulationInfos").value;
console.log("data is: ", data);
</script>