I have a controller which is passing the json object wrapped inside a model.
#RequestMapping("/template")
public String showTemplate(Model model) {
JSONObject obj = new JSONObject();
obj.put("equipmentID", "30584D277D6D4568B17EBB8917D0CB15");
model.addAttribute("template",obj);
return "templates";
}
I would like to use these values in my javascript. I am not able to do that. However, I can see display these values in HTML.
<head>
<script>
function test()
{
var temp = "${template}";
alert(temp); // The values are not displayed here
}
</script>
<body onload="test()">
<span th:text="${template}"> </span> //I can display the values here
<body>
I have also looked into this question How to get spring mvc controller model key value inside javascript? and tried both the options with or without quotes with no success.
I have also tried defining in HTML:
<input type="hidden" id="templates" value='${template}'/>
and using getElementById in my javascript with no success:
var template = document.getElementById("templates");
Using thymeleaf inlining you can use the below:
<script th:inline="javascript">
var message = [[${template}]];
alert(template);
</script>
There are additional ways to access server side variables depending on your use case refer to http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining for more information.
Related
I am sending a filepath ( string) from controller to html page through ViewData and I want to access that string in my javascript, consume it, run some algo in javascript and then use results to consume them and make some graphs on the same html page.
HTML
</head>
<body>
<div id="mychart"></div>
<script>
var path=#ViewData["path"];
//some javascript logic with the string path of the file.
//using results for output chart of id 'mychart'
</script>
</body>
</html>
Controller Action Code:
public IActionResult CellResult(string outputpath)
{
ViewData["path"] = outputPath;
return View();
}
Since it is a string value, you need to wrap it in either single quotes or double quotes.
var path='#ViewData["path"]';
alert(path);
EDIT : As per the comment
How can I send a list of string from controller to html page and use
it in javascript? instead of string i wanna send a list of string
If you want to send a list of string, it is the same, but since it is a complex type now, you need to use the json serializer to convert this object to a string.
So in your server
var list = new List<string> {"Hi", "Hello"};
ViewBag.MyList = list;
and in the view
<script>
var list = #Html.Raw(JsonConvert.SerializeObject(ViewBag.MyList));
console.log(list);
</script>
I'm getting a javascript object via ajax. I need to attach this object to a div in order to be recovered later, for example, on a click event.
If instead of an object I had a variable I would push it into the html tags like this:
'<div variable="'+value+'"></div>';
And I would recover its value like this:
var value= $(this).attr('variable')
Could you suggest me a good approach to do that with objects?
Thank you very much!
The easiest way is to do this:
<div id="myDiv">...</div>
In javascript
var myDiv = document.getElmentById('myDiv');
myDiv._variable = variable;
You can recover this later if you want, simply using the same myDiv variable, or, again, with document.getElementById() or any other DOM method that returns the element.
var variable = myDiv._variable;
The downside of doing it this way is that you can't specify, in the server, or from the markup, which object you want to attach to the element.
If use JQuery you could use the data storrage functionallity
See data documentation of JQuery
//To store value or obj:
$("#myDivId").data("myKey", valueVar);
//Later to load:
var fetchValue = $("#myDivId").data("myKey");
Using a template engine would be the best approach, dividing logic from view, and that way you can parse full object properties to an html.
in this example i use jQuery & UnderscoreJs template engine.
javascript part:
$(document).ready(function(){
var user = { name:"Ofer", age:"29" }
var markup = _.template($("#userTemplate").html(), user);
$('#userContainer').html(markup);
});
html part(goes inside body)
<div id="userContainer">
</div>
<script id="userTemplate" type="text/template">
<fieldset>
<legend>User</legend>
Name: <%= name %><br>
Age: <%= age %> <br>
</fieldset>
</script>
The function _.template($("#userTemplate").html(), user); can be called from within the complete callback function of the ajax, passing the data from the results to the function (user variable would be the data)
Using https://api.jquery.com/prop/
yourObj = [];
//now fill your object with your data
$row = $("td.yourClass")
$row.prop("dataObj", yourObj );
How to set the JSTL variable value in java script?
<script>
function function1()
{
var val1 = document.getElementById('userName').value;
<c:set var="user" value=""/> // how do i set val1 here?
}
</script>
How do I set the 'user' variable (JSTL) value from 'val1' (Java script)?
It is not possible because they are executed in different environments (JSP at server side, JavaScript at client side). So they are not executed in the sequence you see in your code.
var val1 = document.getElementById('userName').value;
<c:set var="user" value=""/> // how do i set val1 here?
Here JSTL code is executed at server side and the server sees the JavaScript/Html codes as simple texts. The generated contents from JSTL code (if any) will be rendered in the resulting HTML along with your other JavaScript/HTML codes. Now the browser renders HTML along with executing the Javascript codes. Now remember there is no JSTL code available for the browser.
Now for example,
<script type="text/javascript">
<c:set var="message" value="Hello"/>
var message = '<c:out value="${message}"/>';
</script>
Now for the browser, this content is rendered,
<script type="text/javascript">
var message = 'Hello';
</script>
Hope this helps.
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
<script ...
function(){
var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";
}
</script>
This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.
Just don't. Don't write code with code. Write a JSON object or a var somewhere but for the love of a sensible HTTP divide, don't write JavaScript functions or methods hardcoded with vars/properties provided by JSTL. Generating JSON is cool. It ends there or your UI dev hates you.
Imagine if you had to dig into JavaScript to find something that was setting parameters in the middle of a class that originated on the client-side. It's awful. Pass data back and forth. Handle the data. But don't try to generate actual code.
You have to use the normal string concatenation but you have to make sure the value is a Valid XML string, you will find a good practice to write XML in this source http://oreilly.com/pub/h/2127, or if you like you can use an API in javascript to write XML as helma for example.
This variable can be set using value="${val1}" inside c:set if you have used jquery in your system.
As an answer I say No. You can only get values from jstl to javascript. But u can display the user name using javascript itself.
Best ways are here.
To display user name,
if u have html like
<div id="uName"></div>
You can display user name as follows.
var val1 = document.getElementById('userName').value;
document.getElementById('uName').innerHTML = val1;
To get data from jstl to your javascript :
var userName = '<c:out value="${user}"/>';
here ${user} is the data you get as response(from backend).
Asigning number/array length
var arrayLength = <c:out value="${details.size()}"/>;
Advanced
function advanced(){
var values = new Array();
<c:if test="${empty details.users}">
values.push("No user found");
</c:if>
<c:if test="${!empty details.users}">
<c:forEach var="user" items="${details.users}" varStatus="stat">
values.push("${user.name}");
</c:forEach>
</:c:if>
alert("values[0] "+values[0]);
});
You can save the whole jstl object as a Javascript object by converting the whole object to json. It is possible by Jackson in java.
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil{
public static String toJsonString(Object obj){
ObjectMapper objectMapper = ...; // jackson object mapper
return objectMapper.writeValueAsString(obj);
}
}
/WEB-INF/tags/util-functions.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<uri>http://www.your.url/util-functions</uri>
<function>
<name>toJsonString</name>
<function-class>your.package.JsonUtil</function-class>
<function-signature>java.lang.String toJsonString(java.lang.Object)</function-signature>
</function>
</taglib>
web.xml
<jsp-config>
<tablib>
<taglib-uri>http://www.your.url/util-functions</taglib-uri>
<taglib-location>/WEB-INF/tags/util-functions.tld</taglib-location>
</taglib>
</jsp-confi>
mypage.jsp:
<%# taglib prefix="uf" uri="http://www.your.url/util-functions" %>
<script>
var myJavaScriptObject = JSON.parse('${uf:toJsonString(myJstlObject)}');
</script>
This is format of JSON data: [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}] that I receive through getjson from server. I need to append json with user input. I am trying to do it in this way: 1st convert it into javascript object, append it with user input, again convert to json object & send it back to server for database update. I have converted json to javaScript object using eval(). Now not able to manipulate javascript object. If I convert javascript object back to json object, it displays correctly all data that was sent from server.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input></p>
<p><input type = "button" id = "send" name = "send" value = "send"
onClick="ADDLISTITEM();"></input></p>
<select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{// this script suffers from errors on eval/JSON.parse methods
alert (json.length);//outputs corrcet with eval
tring = JSON.stringify(json);//outputs corrcet with eval
alert(jsonString);//outputs corrcet with eval
alert(json.options[0]);//no output
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script src="http://www.json.org/json2.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = eval(jsonData);
//json = JSON.parse(jsonData);/*error if uncomment:"IMPORTANT: Remove this line from
json2.js before deployment"*/
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script>
</body>
</html>
In jQuery, $.getJSON()'s callback gets called with parsed JSON data; just use it.
$.getJSON("*.php", function(data) {
$.each(data, function() { alert(this.options); });
);
should give you an alert for every {"options": "xyzzy"} object in the array.
EDIT after OP edited their post:
Your edit clarifies things a little: You won't get any data back -- and it will be completely silent, too, as I found out -- if you violate the same origin policy.
Basically (with exceptions (preflight checks, etc)), you can only access URLs on the exact same domain via AJAX. If your HTML file is a static file served locally, it can not access http://127.0.0.1/; if your file is http://foo.baz.quux.org/, you can't simply AJAX into http://mordor.baz.quux.org .
I don't think the problem here has anything to do with eval/parse etc or the same origin policy. Your json is an array of objects each containing a member named options. Therefore you cannot do json.options[0], you have to do json[0].options.
var json = [{"options":"smart_exp"}, {"options":"user_int"}, {"options":"blahblah"}]
for (var i = 0; i < json.length; i++){
alert(json[i].options)
}
How to set the JSTL variable value in java script?
<script>
function function1()
{
var val1 = document.getElementById('userName').value;
<c:set var="user" value=""/> // how do i set val1 here?
}
</script>
How do I set the 'user' variable (JSTL) value from 'val1' (Java script)?
It is not possible because they are executed in different environments (JSP at server side, JavaScript at client side). So they are not executed in the sequence you see in your code.
var val1 = document.getElementById('userName').value;
<c:set var="user" value=""/> // how do i set val1 here?
Here JSTL code is executed at server side and the server sees the JavaScript/Html codes as simple texts. The generated contents from JSTL code (if any) will be rendered in the resulting HTML along with your other JavaScript/HTML codes. Now the browser renders HTML along with executing the Javascript codes. Now remember there is no JSTL code available for the browser.
Now for example,
<script type="text/javascript">
<c:set var="message" value="Hello"/>
var message = '<c:out value="${message}"/>';
</script>
Now for the browser, this content is rendered,
<script type="text/javascript">
var message = 'Hello';
</script>
Hope this helps.
one more approach to use.
first, define the following somewhere on the page:
<div id="valueHolderId">${someValue}</div>
then in JS, just do something similar to
var someValue = $('#valueHolderId').html();
it works great for the cases when all scripts are inside .js files and obviously there is no jstl available
<script ...
function(){
var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";
}
</script>
This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.
Just don't. Don't write code with code. Write a JSON object or a var somewhere but for the love of a sensible HTTP divide, don't write JavaScript functions or methods hardcoded with vars/properties provided by JSTL. Generating JSON is cool. It ends there or your UI dev hates you.
Imagine if you had to dig into JavaScript to find something that was setting parameters in the middle of a class that originated on the client-side. It's awful. Pass data back and forth. Handle the data. But don't try to generate actual code.
You have to use the normal string concatenation but you have to make sure the value is a Valid XML string, you will find a good practice to write XML in this source http://oreilly.com/pub/h/2127, or if you like you can use an API in javascript to write XML as helma for example.
This variable can be set using value="${val1}" inside c:set if you have used jquery in your system.
As an answer I say No. You can only get values from jstl to javascript. But u can display the user name using javascript itself.
Best ways are here.
To display user name,
if u have html like
<div id="uName"></div>
You can display user name as follows.
var val1 = document.getElementById('userName').value;
document.getElementById('uName').innerHTML = val1;
To get data from jstl to your javascript :
var userName = '<c:out value="${user}"/>';
here ${user} is the data you get as response(from backend).
Asigning number/array length
var arrayLength = <c:out value="${details.size()}"/>;
Advanced
function advanced(){
var values = new Array();
<c:if test="${empty details.users}">
values.push("No user found");
</c:if>
<c:if test="${!empty details.users}">
<c:forEach var="user" items="${details.users}" varStatus="stat">
values.push("${user.name}");
</c:forEach>
</:c:if>
alert("values[0] "+values[0]);
});
You can save the whole jstl object as a Javascript object by converting the whole object to json. It is possible by Jackson in java.
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil{
public static String toJsonString(Object obj){
ObjectMapper objectMapper = ...; // jackson object mapper
return objectMapper.writeValueAsString(obj);
}
}
/WEB-INF/tags/util-functions.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<uri>http://www.your.url/util-functions</uri>
<function>
<name>toJsonString</name>
<function-class>your.package.JsonUtil</function-class>
<function-signature>java.lang.String toJsonString(java.lang.Object)</function-signature>
</function>
</taglib>
web.xml
<jsp-config>
<tablib>
<taglib-uri>http://www.your.url/util-functions</taglib-uri>
<taglib-location>/WEB-INF/tags/util-functions.tld</taglib-location>
</taglib>
</jsp-confi>
mypage.jsp:
<%# taglib prefix="uf" uri="http://www.your.url/util-functions" %>
<script>
var myJavaScriptObject = JSON.parse('${uf:toJsonString(myJstlObject)}');
</script>