<input type="button" value="Place Order" onclick="my()">
<script type="text/javascript">
<% String resp= session.getAttribute("jsonData").toString();%>
const jso="<%=resp%>"
function my(){
alert(jso);
}
</script>
I want to get JSP variable and store in javascript and show in alert but when i di this my onclick function return function my is not defined.
CodePudding user response:
This must work. If not, then there is something else going on
Here I do not add the
<% String resp= session.getAttribute("jsonData").toString();%>
for obvious reasons
window.addEventListener("DOMContentLoaded", () => {
const jso = "<%=resp%>";
document.getElementById("myButton").addEventListener("click", (e) => {
alert(jso);
});
})
<input type="button" id="myButton" value="Place Order">
CodePudding user response:
You probably have a JavaScript error in this line:
const jso="<%=resp%>"
resp
comes from an attribute called jsonData
, and therefore I assume that it contains JSON. Properties and string values in JSON are enclosed in double quotes. The following little example already shows the error I expect you're getting:
const jso="{"key": "value"}"
The opening "
isn't closed by the last "
, but by the first one in your JSON. In other words - you're outputting invalid JavaScript.
The best solution is to properly escape the JSON. I recommend using Apache Commons Text 1.10.0. With the proper import:
const jso="<%=StringEscapeUtils.escapeJson(resp)%>"
This will properly escape any unsafe characters, including "
, in resp
before outputting it.