Passing a variable from Scriptlets to Javascript.

2019-03-01 12:57发布

I have this code snippet ::

<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>

What i want to do is to get the value of variable temp1 in my JavaScript function gotoa(). In this particular code i am getting an error invalid request

request.setAttribute("variable", temp1);

My main aim is to call the function a() on some button click event so that my script let code runs again and fresh values are being passed in variable temp1. which will then passed on to gotoa() to act as a source for my data grid(not in this code). basically i want to refresh grid on some button click. Am i doing the right way. Please help. Thanks.

2条回答
Animai°情兽
2楼-- · 2019-03-01 13:14

First let me tell you couple of things i have observed in this

1) Setting and getting from request needs a page submission otherwise it will not be available in the parameter

2) Scriplet and jsp compiles in different ways, since your scriplet compiliation always happens (no matter where it is header body or footer) first

Now the suggestions for how we can do this

1) Use a EJB object instead of request object

2) Use a hidden input tag to set and get the value needed, assign the getter method to the value of input tag some like ', and when you need to varaible to be changed you need to submit the form, if you do not need to whole page to be reloaded refer ajax methods to change the value alone without reloading the page

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-01 13:26

When you need value of variable temp1 inside gotoa() do the following:

<%  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>

First you assign the value to variable temp1. And then you Render your JSP with a Hidden Input component with value=temp1 by using scriptlet. If you want to verify, just View the Source of generated HTML and you should see the value of input hidden equal to the variable.

When the form is submitted the value of hiddenTemp1 will be available in Request. If you intend to change the value of this hidden component, you can set the value back in the component.

查看更多
登录 后发表回答