2

我有这个代码片段::

<script type="text/javascript">
function gotoa(){
    <%!
    public void a(){
     String temp1;
    PopulateTextbox obj = new PopulateTextbox();
    temp1 = obj.method();
    request.setAttribute("variable", temp1);
    }
    %>


var myVar = <%=request.getAttribute("variable")%>
}
</script>

我想要做的是在我的 JavaScript 函数 gotoa() 中获取变量 temp1 的值。在此特定代码中,我收到错误无效请求

request.setAttribute("variable", temp1);

我的主要目的是在某个按钮单击事件上调用函数 a(),以便我的脚本让代码再次运行,并在变量 temp1 中传递新值。然后它将传递给 gotoa() 作为我的数据网格的源(不在此代码中)。基本上我想在某些按钮单击时刷新网格。我做对了吗。请帮忙。谢谢。

4

2 回答 2

6

temp1当您需要内部变量的值时,gotoa()请执行以下操作:

<%  String temp1; // Store value in temp1 variable for later use
    PopulateTextbox obj = new PopulateTextbox(); 
    temp1 = obj.method();
%>
<script>
function gotoa(){ 

    var temp1Val = document.getElementById("hiddenTemp1").value;
    // put your logic here
    document.getElementById("hiddenTemp1").value = tempVal1;
}
</script>
<body>
<form action="otherPage.jsp">
    <!-- use the value of temp1 variable -->
    <input type="hidden" name="hiddenTemp1" id="hiddenTemp1" value="<%=temp1%>">
    <input type="button" onclick="gotoa()" value="GotoA">
    <input type="submit" value="Submit New Value">
</form>
</body>

首先将值分配给变量 temp1。然后,您使用 scriptlet 使用 value=temp1 的隐藏输入组件呈现您的 JSP。如果要验证,只需查看生成的 HTML 的源代码,您应该会看到 input hidden 的值等于变量。

当表单被提交时, hiddenTemp1 的值将在 Request 中可用。如果您打算更改此隐藏组件的值,您可以在组件中重新设置该值。

于 2012-03-14T09:46:43.567 回答
0

首先让我告诉你我在这方面观察到的几件事

1)设置和获取请求需要页面提交,否则参数中不可用

2) Scriplet 和 jsp 以不同的方式编译,因为你的 scriplet 编译总是首先发生(无论它在哪里是页眉正文或页脚)

现在我们如何做到这一点的建议

1) 使用 EJB 对象而不是请求对象

2)使用隐藏的输入标签来设置和获取所需的值,将getter方法分配给输入标签的值,例如',当您需要更改变量时需要提交表单,如果您不需要要重新加载整个页面,请参考 ajax 方法来单独更改值而不重新加载页面

于 2013-08-27T05:26:18.850 回答