I have an external javascript file called test.js as seen below. This file needs user configuration parameters passed to it, in this case user and show values.
<script type="text/javascript">
<!--//
user = '123';
show = 'appts';
//-->
</script>
<script src="{{ STATIC_URL }}js/widgets/test.js" type="text/javascript"></script>
Above is currently how I tell 3rd parties to add the script to their own site. However, I cannot help to feel this is a bad way to pass these values i.e. clashes.
Is the way I have done it acceptable? Is there a better way?
A simple answer would be to append something to your variable names, such as:
<script type="text/javascript">
<!--//
widget_test_12331_user = '123';
widget_test_12331_show = 'appts';
//-->
</script>
You can stick to namespace convention "reverted domain":
<script type="text/javascript">
<!--//
if (!org) var org = {};
if (!org.mylibrary_domain) org.mylibrary_domain = {};
if (!org.mylibrary_domain.settings) org.mylibrary_domain.settings = {};
org.mylibrary_domain.settings.user = '123';
org.mylibrary_domain.settings.show = 'appts';
//-->
</script>
<script src="{{ STATIC_URL }}js/widgets/test.js" type="text/javascript"></script>
You can use the concept of javascript namespace (How do I declare a namespace in JavaScript?).
so you can add another js file named testConfig.js, which include :
var yourAppNamespaceTestConfig = {
user: function(){ return '123' ;} ,
show: function(){ return 'appts';}
};
then inside test.js, you can read the config by:
var user = yourAppNamespaceTestConfig.user();
var show = yourAppNamespaceTestConfig.show();
And if you're more about OO, try Coffeescript (http://coffeescript.org/). They introduce OO to your javascript.
Related
My actual code is dense, so I'm trying to reduce this to a minimal example.
I have MainUI.js which contains:
var MainUI = function(){
'use strict';
var singleton = null;
class MainUI {
makeSomethingHappen(){
console.log("MAGIC!");
}
}
return {
getSingleton: function(){
if (singleton == null) singleton = new MainUI();
return singleton;
}
};
}();
Then I have test.js which contains:
function test(code){
var uis = MainUI.getSingleton();
retValue = new Function("ui", "use strict'" + code)(uis);
}
This is all run from index.html which contains:
<html>
<script type="text/javascript" src="MainUI.js"></script>
<script type="text/javascript" src="test.js"></script>
<body onload="test('ui.makeSomethingHappen();');">
</body>
</html>
But when I call
test("ui.makeSomethingHappen();");
or even
test("console.log('NARF!');");
I get an exception with the message
MainUI is not defined
The singleton accessor and the MainUI works in all my code outside of "new Function()", so I know it's working (even if I made typographical error producing the minimal test).
So I'm hoping someone can tell me how I can give the code inside the Function access to the class definitions outside.
Make sure that the MainUI.js script is referenced correctly and that it is referenced prior to the test.js script that will use it.
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 function that I wrote and embedded in an .aspx page. I declared variables at the top of the function that access ConfigurationManager.AppSettings and also the sessionState tag as follows:
var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
var Value2 = "<%= Session.Timeout %>";
This function has been working just fine. I've realized that I will need to use the function across four other pages so I decided to move it to an external JavaScript file. According to this question and accepted answer...
Accessing ConfigurationManager.AppSettings in Java script
...external JavaScript files do not evaluate code inside of these "server-side code" tags, therefore, values from the web.config file must be passed from the .aspx page as parameters. I moved the function to an external JavaScript file and call the function like this:
<script src="Scripts/JavaScript.js" type="text/javascript">
var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
var Value2 = "<%= Session.Timeout %>";
externalFunction(Value1, Value2)
</script>
The external JavaScript functions begins as follows:
function externalFunction(Value1_, Value2_) {
debugger;
var Value1 = Value_1;
var Value2 = Value_2;
...
}
As I debug the JavaScript function, the arguments themselves are undefined. What am I missing here?
Update - 4/12/17
I have tried calling the function in both of the following ways.
<script src="Scripts/JavaScript.js" type="text/javascript">
var Value1 = "1";
var Value2 = "2";
externalFunction(Value1, Value2);
</script>
<script src="Scripts/JavaScript.js" type="text/javascript">
var Value1 = "1";
var Value2 = "2";
</script>
<script src="Scripts/JavaScript.js" type="text/javascript">
externalFunction(Value1, Value2);
</script>
Using IE's debugger, I can see that the values were pulled correctly from the web.config file, but the function still is not being called. I'm stumped.
Try with two separate script tags, and see any different.
<script src="Scripts/JavaScript.js"></script>
<script type="text/javascript">
var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
var Value2 = "<%= Session.Timeout %>";
externalFunction(Value1, Value2);
</script>
This is based on the scala-js-example-app from GitHub.
I have a function that I want to define in Javascript and is not already defined by the Scala.js library.
In my copy of the ScalaJSExample.scala file, I have:
object Mine extends js.Object {
def foobarfoo():String = ??? //this is just a simple example and I know this can be done completely in Scala, but just go with it.
}
object ScalaJSExample extends js.JSApp {
def main(): Unit = {
val paragraph = dom.document.createElement("p")
paragraph.innerHTML = "<strong>It works!" + Mine.foobarfoo() + ".</strong>"
dom.document.getElementById("playground").appendChild(paragraph)
}
/** Computes the square of an integer.
* This demonstrates unit testing.
*/
def square(x: Int): Int = x*x
}
Now I want to define foobarfoo in Javascipt.
I've tried writing this in a javascript file:
function foobarfoo() { return "Hello, World!"; }
and that didn't work, so I tried a more Scala.js syntax:
var Mine = {
foobarfoo: function() { return "Hello, World!"; }
}
and many other variations, but none of these worked and I couldn't get "Hello, World!" to appear on the webpage after compilation.
How should I write foobarfoo() so that I get the right result?
Resuming the discussion, the problem was the inclusion order: The OP added the custom JavaScript functions after the Scala.js code:
<script type="text/javascript" src="./target/scala-2.11/example-opt.js"></script>
<script type="text/javascript" src="./target/scala-2.11/example-launcher.js"></script>
<script type="text/javascript" src="src/main/scala/example/myscript.js"></script>
Therefore, the requested function couldn't be found. Putting myscript.js to the top solved the issue:
<script type="text/javascript" src="src/main/scala/example/myscript.js"></script>
<script type="text/javascript" src="./target/scala-2.11/example-opt.js"></script>
<script type="text/javascript" src="./target/scala-2.11/example-launcher.js"></script>
I just need your help about my code. My problem is how can I access smarty variable within jquery or javascript file? Becuase my smarty variable is a URL request from my controller. And I need to use that variable for creating validation. Here's my code.
{$get.search_by} {**works without error**}
{literal}
<script type="text/javascript">
$(document).ready(function(){
var dispatch = "{$get.search_by}"; //can't access
var new_class = "it3 ir3 il3 jt10 jr05 jl05 kt03 kr04 kl04";
var old_class = "it3 ib3 il3 jt05 jb05 jl10 kt04 kb04 kl03";
var toggleState = true;
//could not access
if(dispatch == companies.catalog){
alert("catalog");
}else{
alert("product search");
}
console.log(dispatch);
Try this code
var dispatch = '{/literal}{$get.search_by}{literal}'
To make things cleaner, you can move the {literal} tag down and also escape the $get.search_by variable (in case search_by may have a string with a quote i.e. "let's try"):
<script type="text/javascript">
var dispatch = '{$get.search_by|escape:'javascript'}';
{literal}