I'm adding an attribute to my ModelAndView in spring and after this i forwarding it to my thymeleaf view.
In the view i have the following code:
<script th:inline="javascript">
/*<![CDATA[*/
var applicationName = /*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/ "Test";
var collectedValueJson = [[${collectedValues}]];
console.log(collectedUserJson);
/*]]>*/
</script>
Result from this is
var applicationName = 'collectedValues';
var collectedUserJson = '[{\"givenname\":\"Muster\",\"surname\":\"Peter\"}]';
That's fine. Now my wish for this is, that i can take the var application and access with this variable the modelattribute, but that's not working.
Result is this:
var tmp2 = ${applicationName};
An other try was, that i have access to the modelattribute with the syntax /*[[ ]]*/ from the first try:
var applicationName = ${/*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/};
But result will be:
var tmp = ${'collectedValues'
i have no idea what can i try.
Any other suggestions?
Thank's in advance.
There is a workaround worth mentioning: Write out the attribute to
<span id="myvar" th:text="${attributeName}"></span>
and then read it in with JavaScript using
document.getElementById("myvar").value
or some similar jQuery call:
$('#myvar').text()
there is no way you can access model atributes hence they are on server side and they where lost when rendering jsp into HTML
You can:
<span id="span_id" style="display: none;" th:text="${attributeName}"></span>
and then in your Javascript:
document.getElementById("span_id").innerHTML
Related
Hi I have the following TextArea to display a JSON string:
<TextArea id="payloadlabel" width="1000px" height='auto' rows='80' />.
My problem is that the JSON string is not well formatted, see example.
I'm using the library vkbeautify as follows:
var myObj = {
"urn.getxxxx": {
"urn.xxxx" : "cxxxxx-44e9-xxxx-a91b-0000xxxx\\xxxxx\\3xx\\xx\\x\\",
"urn.xxxx" : "xxxxx",
"urn.xxxxx" : "x",
"urn.xxxx": "20xx-07-08xxx:03:41+02:00"
}
};
var request = JSON.stringify(myObj);
vkbeautify.json(request);
var tryModel = new sap.ui.model.json.JSONModel();
tryModel.setData(request);
var payloadtxta = sap.ui.getCore().byId(view.createId('payloadlabel'));
payloadtxta.setModel(tryModel);
payloadtxta.setValue(request);
Unfortunately it's not working. The JSON content remains exactly like in the example. What is wrong here?
I have the vkbeautify.js file in my web content and I included it in the index.
<script type="text/javascript" src="vkbeautify.js"></script>
As I get no error for the vkbeautify method I think I included it in the right way. Suggestions are welcomed if you know any other method to format JSON content any other library or idea. Thank you.
You are using the wrong variable (BTW: JSON.stringify is superfluous as you already have a JSON string):
var beautifiedObj = vkbeautify.json(myObj);
var payloadtxta = this.byId(view.createId("payloadlabel"));
payloadtxta.setValue(beautifiedObj);
The model is never used in your example, thus you can remove it or use it as intendend by UI5 and bind the control directly to the model property.
<TextArea id="payloadlabel" value={/request}" width="1000px" height='auto' rows='80' />.
this.setModel(new sap.ui.model.json.JSONModel({
"request" : vkbeautify.json(myObj)
});
Looking at the source of vkbeautify, it is slightly pointless if you are just using that library for this purpose - you can do what you need with standard JavaScript:
var beautifiedTxt = JSON.stringify(myObj, null, 4);
var payloadtxta = sap.ui.getCore().byId(view.createId("payloadlabel"));
payloadtxta.setValue(beautifiedTxt);
Check out the documentation of JSON.stringify on MDN here - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
REF source for vkbeautify - https://github.com/vkiryukhin/vkBeautify/blob/master/vkbeautify.js#L152.
I have a JavaScript program that worked until I tried to change this: "foldername" to this: http://hokuco.com/test/"+"foldername"+"/index.html".
what is wrong with my code?
For anyone interested entire JS:
document.getElementById("submit").addEventListener("click", function(){
var url = document.getElementById("http://hokuco.com/test/"+"foldername"+"/index.html").value;
window.location.href = "url";
});
<input type id="foldername"></input>
<input type ="button" id ="submit/>
You probably meant:
document.getElementById("submit").addEventListener("click", function(){
var url = "http://hokuco.com/test/" + document.getElementById("foldername").value + "/index.html";
window.location.href = url;
});
Changes:
The parameter in the getElementById function is the same as the id attribute on the input element with the id "foldername".
The window.location.href should be set to a variable, not a quoted string.
More legibly, you would want:
document.getElementById("submit").addEventListener("click", function(){
var folder = document.getElementById("foldername").value;
var url = "http://hokuco.com/test/" + folder + "/index.html";
window.location.href = url;
});
Now, hopefully, it is much more clear about what's going on.
Please read the following documentation to better understand document.getElementById: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Your code will most likely return an uncaught type error when trying to access a property of null. You must only pass a string referring to an Element object's ID.
What are you trying to accomplish? It looks like you are trying to redirect but are using a string literal instead of a variable.
I am using Thymeleaf as template engine. How I pass a variable from Spring model to JavaScript variable?
Spring-side:
#RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("message", "hello");
return "index";
}
Client-side:
<script>
....
var m = ${message}; // not working
alert(m);
...
</script>
According to the official documentation:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
console.log(message);
/*]]>*/
</script>
Thymeleaf 3 now:
Display a constant:
<script th:inline="javascript">
var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";
</script>
Display a variable:
var message = [[${message}]];
Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).
Thymeleaf calls this: JavaScript natural templates
var message = /*[[${message}]]*/ "";
Thymeleaf will ignore everything we have written after the comment and before the semicolon.
More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
var message =/*[[${message}]]*/ 'defaultanyvalue';
According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.
1) Simply put the variable from server to javascript :
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
alert(message);
/*]]>*/
</script>
2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:
<script th:inline="javascript">
/*<![CDATA[*/
function sampleGetByJquery(v) {
/*[+
var url = [[#{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]]
+ "&var2="+v;
+]*/
$("#myPanel").load(url, function() {});
}
/*]]>*/
</script>
The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).
MAKE sure you have thymleaf on page already
//Use this in java
#Controller
#RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
model.addAttribute("showTextFromJavaController","dummy text");
return "showingTymleafTextInJavaScript";
}
//thymleaf page javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>
I've seen this kind of thing work in the wild:
<input type="button" th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />
If you use Thymeleaf 3:
<script th:inline="javascript">
var username = [[${session.user.name}]];
</script>
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [( brackets which wrap the variable.
Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html
One way to handle this is to create a dynamic javascript file with the
URLs embedded in it. Here are the steps (if you are using Spring MVC)
#RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public String dynamicJS(HttpServletRequest request) {
return "Your javascript code....";
}
Assuming request attribute named "message":
request.setAttribute("message", "this is my message");
To read it in the html page using Thymeleaf template:
<script>
var message = "[[${message}]]";
alert(message);
</script>
I have a javascript variable
var url = http://www.abc.it/it/security/security.aspx?security=pdfcompare&../securitycomparepdf/default.aspx?SecurityTokenList=blab]2]0]blab$ALL|blab]2]0]blab$ALL|blab]2]0]blab$ALL;
I need to remove the part "../securitycomparepdf/default.aspx?" from it using jquery, so that the variable becomes
http://www.abc.it/it/security/security.aspx?security=pdfcompare&SecurityTokenList=blab]2]0]blab$ALL|blab]2]0]blab$ALL|blab]2]0]blab$ALL;
Can someone please suggest?
Thanks
Made a demo for you: http://jsfiddle.net/B3Uwj/27/ (from #tats_innit)
url = url.replace("../securitycomparepdf/default.aspx?", "");
Use the following JS
var url = "http://www.abc.it/it/security/security.aspx?security=pdfcompare&../securitycomparepdf/default.aspx?SecurityTokenList=blab]2]0]blab$ALL|blab]2]0]blab$ALL|blab]2]0]blab$ALL";
url = url.replace("../securitycomparepdf/default.aspx?","");
alert(url);
See a live example here
I am responding to clicks on li's by using $.post to post to an action method in my MVC application.
I want to send a link back in Json.
Can I have this link render as html rather than text ? how ?
I tried this, just to test the html:
var link = "<b>Hi</b>";
var encoded = Server.HtmlEncode(link);
that came out as <b>Hi</b>
Surely there is just a Json.encode or visual studio method I can use and I don't have to format it myself? Have googled fairly extensively and can't find anything about an Json.encode
var link = "<b>Hi</b>";
var encoded = new JavaScriptSerializer().Serialize(link);
the page rendered "\u003cb\u003eHi\u003c/b\u003e"
If I send just the link variable, i.e:
var link = "<b>Hi</b>"
<b>Hi</b> renders
This is the line which sends it back:
return Json(new {Title = pTitle, Selection = pSelection, Link = pLink}, JsonRequestBehavior.AllowGet);
Starting to get frustrated, wtf!
Silly me, I didn't post enough code where the problem was:
<script type="text/javascript">
function TreeView_onSelect(e) {
...
$.post(url, id, function (data, textStatus) {
...
$("#panel-link").text(data.Link);
}
$("#panel-link").text(data.Link);
obv has to be
$("#panel-link").html(data.Link);
Try using JavaScriptSerializer:
var link = "<b>Hi</b>";
var encoded = new JavaScriptSerializer().Serialize(link);
Try to use javascript's decodeURI() function.
http://www.w3schools.com/jsref/jsref_decodeuri.asp
<script type="text/javascript">
var uri="mytest.asp?name=ståle&car=saab";
document.write(encodeURI(uri)+ "<br />");
document.write(decodeURI(uri));
</script>
The output of the code above will be:
mytest.asp?name=st%C3%A5le&car=saab
mytest.asp?name=ståle&car=saab
I have the same problem with you and killing me whole day,
I solved this problem by using Json.NET
Sample code is :
Newtonsoft.Json.JsonConvert.SerializeObject(link);
Reference
http://json.codeplex.com/documentation