This question already has answers here:
Pass Javascript Value to Java in JSP
(2 answers)
Closed 7 years ago.
New to learning JSP, and trying out passing data between two pages.
I'm wondering if it is possible to pass a javascript variable to session.setAttribute()
At the moment, I can pass a string of text through 2 jsp files like so:
JSP1:
<% String text = "hello";
session.setAttribute("test", text);%>
JSP2:
var someText = "<%=session.getAttribute("test")%>"
which works fine.
However, is it possible to pass through a var into session.setAttribute instead? I store some data in a javascript variable and would like to send it across to the second JSP file.
So for example:
var number = 7;
<%session.setAttribute("test", number);%>
I've tried this out and I get the error "number cannot be resolved to a variable"
Thanks!
You cannot do that since javascript executes on client & JSP executes on server side.
If you want to set javascript variable to JSP session, then you pass this variable through the URL like this
var number = 7;
window.location="http://example.com/index.jsp?param="+number;
Now receive this var in your JSP page like this
String var = request.getParameter("param");
Now set it in session
session.setAttribute("test", var);
EDIT :
var number = 7;
<%session.setAttribute("test", number);%>
In the above code, server will only execute the code inside <% %>. It does not know anything outside of the JSP tags. So, it will also dont know about your javascript variable number.
Server executes the code & the result will be sent to the browser, then your browser will execute that javascript code var number=7;.
Hope, now it is clear for you.
Related
This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 4 years ago.
Essentially I have one HTML Script, in the javascript portion of the HTML code, I have a few variables. Essentially how do I get those values to interact with another url location.
To rephrase, Let's say I have this URL, containing the variables in that script: www.example.com/stuff. Now I want to use those variables to interact with www.example.com/stuff2.
How would I do that?
You can use locaStorage or sessionStorage for that:
In one page use:
<script>
let var1 = "some data";
let var2 = "other data";
localStorage.setItem("data", {var1, var2});
</script>
In the other page get the data previously saved using:
<script>
let data = localStorage.getItem("data");
console.log(data.var1);
console.log(data.var2);
</script>
Note: The same syntax works for sessionStorage
If I correctly interpret your question, the solution would be to link the javascript also on the second page with <script> </ script>
You can assign variable globally
file 1
window.var1 ="value"
file 2
window.var2 = window.var1;
I have a requirement where i need to pass a value from Javascript to a Scriplet in a JSP. i am aware that javascript is executed on client side and jsp on the server side.i have searched online and googled a lot but till now i am not able to find a solution that i am looking for. The JSP code is as below. both javascript and scriplet are in same jsp.
<script type="text/javascript">
var strUrl = window.location.href;
var aps = strUrl.toLowerCase().indexOf("values");
var modifiedString = strUrl.substring(aps+8);
var v = strUrl.indexOf(modifiedString);
document.write(v);
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st);
if(st.equals("0")){
out.println("test");
%>
<h1><div class="xyz">
<fmt:message>header.txt</fmt:message>
</div></h1>
<%
}else{
%>
<div class="pqr">
<fmt:message>header1.txt</fmt:message>
</div>
<%
}
%>
In the above code i am trying to pass a value from Javascript to a scriplet.
But i am getting a NumberFormatException when i try to parse that string and convert to int. looks like the variable st is not of a string type.
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st)
Can you please let me know what is the problem with the above code and how can i resolve the problem that i am facing now.
Thanks
Vikeng
The reason why you can't parse "<script>document.writeln(v)</script>" as an int is because it contains characters other than digits.
Even though it looks like it contains <script> tags - it's still not code that will execute or evaluate to a number. Because it's in quotes it's just a string. So "<script>document.writeln(v)</script>" looks the same to the parser as would "tic/v)neiwtm>oprs<citdun.rtl(<rp>".
This is somewhat of a moot point however, because unfortunately, you can't pass values to scriptlets. It's completely one-directional.
In order to get your page communicating with your java, you'll need to pass your params while requesting some handler.
For example, you could do some asynchronous JavaScript:
var asyncHR = new XMLHttpRequest();
var URL = "https://www.yourserver.com/intparser?st=v";
asyncHR.open("GET", URL, true);
asyncHR.send();
Then your request handler could take that parameter st, parse it or whatever you need to do, modify the model - adding this new value as an attribute, and then from JavaScript, reload the page.
This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 8 years ago.
I have written a simple code in a .js file (in Zend framework, but I dont think it matters)
var location = "localhost:8080/mymodule/id/1#";
location.replace(/\#/g, "");
alert(location.valueOf());
return;
but I dont know why I can not see the result I want.
I get my page url and want to omit all number signs appears in it. but the code above does nothing.
please help
location is a bad name to use for a variable since it collides with the window.location variable used for the actual browser page location.
If you change location to loc in your above code, and then also add loc = in front of the loc.replace() call (since replace() doesn't modify the input, but instead returns the new version), your code works.
replace will not change the value of the original string, you need to assign the result to a new variable -
var newString = location.replace(/#/g, "");
alert(newString);
Demo - http://jsfiddle.net/5H5uZ/
It can be done in one line. This is the result you look for?
alert("localhost:8080/mymodule/id/1#".replace(/#/g,''));
//=> alerts 'localhost:8080/mymodule/id/1'
I want to call a javascript function from my ASP.NET (C#) code, I want to pass a variable (string) with another string like below:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text'+'"+myString+"'<br/>'another text);");
how should I pass these values? also I want to have new line in my tooltip (<br/>), what should I do? I've tried several ways (using ', + and other methods) to send all these values but I get javascript error, is there any sample? please help me
thanks
In that function, you could use the server side code tag.
var string = "<% = myString%>"
You are very close, keep in mind that when controls are generated on the server they are 'unrolled' into HTML on the client -- in other words the '+' sign is unnecessary as the client will only ever see the string (it has no notion of which part of the attribute value was generated in code vs. which part is hard coded on the server).
var toolTip = string.Format("This is text was added on {0}:{1}<br />this text is hard-coded", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()
var attributeValue = string.Format("tooltip.show('{0}')");
tag.Attributes.Add("onmouseover", attributeValue);
Try this:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text','"+myString+"<br/>another text');");
Two ways:
Method 1 (Jon Martin's way): Have a javascript variable populated by server information
Create a javascript variable on the aspx page: var myString = '<%= _mytring %>';
Populate _mystring on the code behind: public String _mystring = "your value";
Method 2: Just dump the variable out from the server side
Page.ClientScript.RegisterStartupScript(getType(Page), "var myString = '" + "your value" + "';", true);
Ok so in my mvc View my "Model" is a list of objects and in this case i want to get a specific Id of one of the objects.
var counter = 0; //for example
var id = '<%=Model[' + counter + '].Id %>';
This is what i get :
Compiler Error Message: CS1012: Too many characters in character literal
Thanks!
Yes, the counter variable can't be used as the index for Model[], because it only exists on the client (assuming this snippet was inside of a script html element). When you are creating a view, it might be useful to think of it as a long 'string' that you are constructing (the html returned to the browser). In this case 'counter' is just some characters in your script block that will eventually be interpreted by the browser, so it's not a variable that can be used while building the view. The <%= %> block just returns a string to append (that's what the = sign does).
Perhaps you intended to have the counter variable in it's own C# code block like so:
<% var counter = 0; %>
<script language=javascript>
var id = '<%=Model[counter].Id %>';
</script>
That doesn't really make any sense. You're trying to put together an ASP expression with client-side Javascript in the middle of it. It's nonsensical because the ASP stuff all runs on your server, while the Javascript runs in the client.
Without knowing the rest of what you want to do, it's hard to say how you should proceed.