Is there any way to call #controllers.app.test() by the Javascript?
It has been working fine while using
location.href = '#controllers.app.test()'
And somehow this location.href became an actual URL:
127.0.0.1:9001/admin/#controllers.app.test()
Can anyone help me out with this?
The #controllers.app.test() is calculated on the server side. Your HTML is in the view and processed by the server, that's why it becomes /admin/#controllers.app.test(). Your Javascript is just in a public folder, so it does not process.
What you can do one of the next:
Put JS file into the view (the same place where your HTML that "works fine" is placed).
Add JS object to the HTML like <script> var myAction="#controllers.app.test()"</script> and then use myAction in JS.
Use Java Script router:
3.1. https://www.playframework.com/documentation/2.6.x/ScalaJavascriptRouting
3.2. Convert a javascript variable to scala in play framework
3.3. How to update src of a img from javascript in a play framework project?
Related
I'm trying to figure out how to organize my javascript/django code.
So far I used to put my javascript page specific code in the same file. i.e I embed javascript in a <script> tag inside the template.
This creates a lot of mess when my JS code become large:
- django template variables {{var}} inside my JS code does not look well,
- I get an error when I try to minify it with tools like this one: http://jscompress.com/ ,
- And I just try to separate them as much as possible.
Today, in my embeded <script> tag my JS code looks like:
var app = {
func: function() {
// can I use the {% url %} tag here ?
$.post('/url/', {csrfmiddlewaretoken:'{{csrf_token}}', something:'value'} )
},
jsonFromServer: '{{pythonDict|safe}}', // I need this data structure,
};
As you can see, there are some values I need to pass form django to javascript, the most common is the csrftoken, for ajax requests. But sometimes I also pass a json dictionary that is needed for the app itself. Sometimes I want to pass the server time as well.
I'm thinking of moving the JS code to a separate file, I read that it is better way to organize like that. But I can't see how it is possible in a normal django app, without django have to render the .js files. And I believe it is better the JS file won't be served by django?
So how could I organize my JS without too much django code in it ?
I Don't know if it's "beautiful" but usually, I organize my code like that when it's about make web dev in MVC:
I put my <script> tag in the template of my page.
I write my js in an external file, traditionally in the /static/JS/my_template_name.js
As my gobal layout can have some JS code too, I make a great use of the JS modules: https://medium.freecodecamp.com/javascript-modules-a-beginner-s-guide-783f7d7a5fcc#.bjf4xwuq4
Usually, I don't have to do that.
When I need var from server in my js code, I make some Ajax calls.
But if you really want to process like that, I can suggest you to do something like this in your template:
<script>
var from_server = {{vars_from_server}};
</script>
Normally, if you pass a variable named vars_from_server to your template it will replace the placeholder between the script tags. Just think to format "vars_from_server" in a correct JS way.
After that, you will be able to access your vars in your scripts by accessing from_server variable from anywhere.
The question is as following: when I write JavaScript inside my JSP page, using JSTL function, it renders normally, understanding everything I want from it. But to make my code clear, I want to move that JavaScript from tag in JSP to a separate file. But when I try to call same function from the file, it doesn't work, but just appends to my page as a simple text.
Here is code example to make this more understandable.
...other JSP stuff
<script>
$.each(data, function(index, item) {
$('#holder').append(
'<tr>' +
'<td>item.price + ' <fmt:message key="currency.default"/></td>'
'</tr>'
);
});
</script>
This works perfect for me. The actual message from the resource bundle is pulled and set instead of the fmt:message function.
But when I move the same code to a separate file, all this doesn't transform and stays plain text.
I understand, that JSP serves on the server, and all transformations with those functions is done much earlier than actual javascript is loaded.
But maybe somebody knows a certain hack to make this work?
Thanks in advance.
You can use DWR for that cause. An old framework but still holds good if that is what exactly you are looking for in your question.
http://directwebremoting.org/dwr/index.html
DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.
Running java methods or jstl functions(also jstl functions are java methods) from JavaScript is impossible. Because java methods run on server-side but javascript on client-side.
If you want to run java methods in client-side anyway you must create java applet for this. You can run java methods with JavaScript inside your applet. For detailed information see this Java Applet Tutorial
I hope this will help you
I use a .cshtml file to generate a dynamic .js file in an ASP.NET MVC controller. So the .js file never exists on disk, but only in memory at runtime. It works like this.
The browsers loads a javascript...
<script async src='http://example.com/script.js'></script>
...that is fetched from and generated by my MVC Controller endpoint:
[HttpGet]
[Route("script.js")]
public ActionResult GetScript()
{
// This takes a .cshtml template-file and returns a generated .js file
return new JavascriptViewResult(viewName, viewModel);
}
Is there a way to minify the resulting javascript file that is returned in runtime? I had a look at System.Web.Optimization.JsMinify but I'm not sure how I would get that to work. Can I write some kind of HttpHandler? Is there maybe a better approach to solve this problem?
I had a similar problem and after some searching some I came across this question. All you need to do is:
using Microsoft.Ajax.Utilities;
//...
string minifiedScript = new Minifier().MinifyJavaScript(yourJs);
I can't believe it was this simple, yet so hard to find.
P.S. It seems to be part of Microsoft Ajax Minifier library, but I don't remember ever installing it manually, so it's either part of MVC or comes with System.Web.Optimization.
I didn't notice the part about the JS being generated from a view. In that case using bundles might be a solution or rendering the view to a string (but I'm unfamiliar with how it's done in Spark view engine) before passing it to Minifier.MinifyJavaScript.
Edit: Another solution (albite somewhat convoluted) would be calling Minifier.MinifyJavaScript in the view and cramming the actual JS in a partial view. I don't know about Spark, but in Razor it's fairly easy to render a view to string from another view.
I have an old web app developed in ASP.Net with the old type code behind style. I am eventually going to re-do the complete web app in ASP.Net MVC 3 - just starting to complete the first sections and integrate them. I am having some problems with a menu that appears along the top. So there is a home button it looks like the below in code:
onclick='document.location.href=\"Home.aspx\"'>
However I am getting the url in the new mvc part of web were I have the menu and i try to hit the home icon I get a page not found:
/MyWeb.Web.App/mvc/Controller/Home.aspx
The actual home aspx page exists in the location \MyWeb.Web.App\mvc\Home.aspx
I am currently stumped as to what I can edit in the JS href to get it to point to this location so the icons will work in the existing implementation and the new MVC one.
Thanks.
Use urls helpers. For example if you are using Razor and this code is inside an MVC view:
onclick='document.location.href="#Url.Content("~/mvc/home.aspx")"'>
or if you are using the WebForms view engine:
onclick='document.location.href="<%= Url.Content("~/mvc/home.aspx") %>"'>
UPDATE:
If this is in a separate javascript file then you could declare a global variable inside your Razor view that will point to the base url:
<script type="text/javascript">
var baseUrl = '#Url.Content("~/mvc")';
</script>
and then inside your javascript file:
onclick='document.location.href=\"" + baseUrl + "/home.aspx\"'
There are of course much better ways to achieve that but since you haven't provided enough details about your scenario it's difficult to suggest what might be best. For example you could use HTML5 data-* attributes in your DOM or some other elements to generate properly this url and access it in your javascript file.
I am trying to create a Silverlight class library which needs to call a few Javascript methods. I have put these methods in a single .js file and have added it to the project. But when I try to call any of the methods in the js file, I get a FailedtoInvoke error. I understand that this problem can be solved by adding a reference of the JS file in the head section of ASPX or HTML page. But I am developing a class library and so that is not possible. Does someone know how to tackle this issue? I am using Silverlight 4 and Visual Studio 2010.
Add the .js file to your library probject as it sounds you have done, make sure it Build Action is "Resource".
You can retrieve this content with Application.GetResourceStream :-
StreamResourceInfo sriJS = Application.GetResourceStream(new Uri("YourAssemblyName;component/MyStuff.js", UriKind.Relative));
Note the structure of the Uri, the assembly name of your class library is needed followed by the literal ";component". This tells Silverlight to look for a resource inside your dll that will be included in a final application's Xap.
Now you need to turn the content of the info's Stream property into a string:-
StreamReader reader = new StreamReader(sriJS.Stream, System.Text.Encoding.UTF8);
string js = reader.ReadToEnd();
Finally you can inject that javascript into the current page with:-
HtmlPage.Window.Eval(js);
Thats it, any global functions defined in the js may now be invoked with HtmlPage.Window.Invoke.
Try something like:
string myScriptCodeString = GetScriptCodeStringFromSomewhere();
System.Windows.Browser.HtmlPage.Window.Eval(myScriptCodeString);
Then the methods defined in myScriptCodeString should be available.