I am trying to use a JSP variable in a .js file, but it doesn't populate anything in the variable. However, if I do the same in the jsp file inside block, it works fine. In other words:
Scenario#1
test.jsp (keeping everything in a jsp file) - works fine!!!
final String[] CONTENT = Processor.getContent();
final String projects= CONTENT[0];
<script>
function createPDD($container) {
var $projects = JSON.parse('<%=projects%>'); // this works fine and show the list of projects.
}
</script>
Scenario#2 test.jsp (keeping the js code .js file) - doesn't work!!!
<script src="test.js"> </script>
final String[] CONTENT = Processor.getContent();
final String projects= CONTENT[0];
test.js
function createPDD($container) {
var $projects = JSON.parse('<%=projects%>'); // this doesn't work... $projects comes empty.
}
Please note, its not a js import path issue as other js functions in test.js work fine.
Related
Hi I am new to android development,
In MainActivity.java I have webview (refer to one HTML file in loadurl eg: index1.html) and button, on clicking the button, I make a call from java to js(app.js refered in index1.html ) file where I will form an object (like map structure) and assign to a variable, then I will trigger another activity(Main2Activity.java) using Intent intent = new Intent(this, Main2Activity.class)
The Main2Activity.java also have webview (refer to one HTML file in loadurl eg: index2.html) now I have to access the variable in app1.js(index2.html) that variable was created in app.js (index1.html)
Like localstorage in js.
What changes I have to do. Thanks in advance :)
MainActivity.Java code given below:
public void ViewPdf(View view) {
WebView.loadUrl("javascript:getDetails()");
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
app.js code :
var getDetails = function(){
// the below variable I need to access in another js file that is in index2.html
details = {
date : $(".mainDate .date").val(),
no : $(".maniNo .No").val(),
shopNo: $(".shopNoIn").val(),
itemDetails : itemMap
}
}
app2.js code:
$(document).ready(function () {
// the valiable that is set in app.js()index1.html
updateBill(details);
});
While trying to create a rich text editor, I cannot seem to add the js script for the buttons and form. Right now, most of the functions are inlined in the jade pages, but that is quite unelegant.
I have a layout.jade file:
doctype html
html
head
body
header
section.content
block content
And the create.jade script, where I want the rich text editor:
extends ../layout
block content
script(type='text/javascript', src='./css/js/wiz.js')
form(method="post", action=post ? '/post/edit/' + post.id : '/post/create', onload="iFrameOn()")
ul
p
input#title(name="title", placeholder="Title", value=post ? post.title : '', autocomplete='off')
p
#wysiwyg_cp(style="padding:8px; width:700px")
input(type="button", onClick="iBold();", value="B")
input(type="button", onClick="richTextField.document.execCommand(\"underline\",false,null);", value="U")
p
textarea#blogPostBody(style="display:none", name="blogPostBody", placeholder="Blog post text", rows="20", cols="50")
iframe#richTextField(name="richTextField", contentEditable="true", onLoad="richTextField.document.designMode = 'On';")
if(post)
| #{post.body}
else
| 	
p
input(onClick="javascript:submit_form();", type="button", name="myBtn", value="Save")
The structure of the project looks like:
Proj
- css
-- js
--- wiz.js
- middleware
- node_modules
- public
- routes
- views
-- post
--- create.jade
-- layout.jade
-- home.jade
-- login.jade
- app.js
- package.json
When trying to open the create section of my blog, I get the following error message, as can be seen in the image below:
Uncaught SyntaxError: Unexpected token <
See chrome stack: http://i.stack.imgur.com/JyHs2.png
The wiz.js file looks like this:
function iFrameOn() { richTextField.document.designMode = 'On'; }
function iBold() { richTextField.document.execCommand("bold",false,null); }
function iUnderline(){ richTextField.document.execCommand("underline",false,null); }
function iItalic(){ richTextField.document.execCommand("italic",false,null); }
function iImage() {
var imgSrc = prompt("EnterImageLocation", '');
if(imgSrc!=null) {
richTextField.document.execCommand("insertimage",false,imgSrc);
}
}
function submit_form() {
var theForm = document.getElementById("myForm");
theForm.elements("myTextArea").value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
I have also tried adding
app.set('view options', {locals:{scripts:['wiz.js']}});
and/or adding
app.use(express.static("./css/js"));
In the app.js file or in the middleware.
But these did not help. The problem seem to be in the "create.jade" script, when referencing the 'text/javascript' script, because the same error was obtained even when referencing a non-existant js file.
Could anyone have any idea what the problem could be?
[EDIT] SOLUTION that was implemented:
script
include ./../../css/js/wiz.js
The following snippet of code worked:
script
include ./../../css/js/wiz.js
Express's static middleware will by default mount the files to the root. So, if you include the middleware as above, the wiz.js file will be accessible at "/wiz.js" when your server's running -- this is the path you should put in the src attribute of your script tag in the jade file, not the local path (since local files are not accessible to the client unless they are served). If you want to change the mountpath (so, for example, that the file will be accessible on "/js/wiz.js", rather than the root), you can add it as a first argument, like below:
var localDirectoryPath = "./css/js";
// Or if you happened to want an absolute path
// (though it doesn't make a difference here):
// var localDirectoryPath = require("path").join(__dirname, "css", "js");
app.use("/js", express.static(localDirectoryPath));
The temporary solution that you've found (using Jade's include function) is merely loading the file's contents on the server (when Jade compiles the template) and inserting the code in between script tags on your page, which works but is certainly not ideal, since it will slow down the initial loading of your HTML, especially as the wiz.js file gets bigger.
And I won't even ask why your javascript directory is inside your css directory!
I get a variable from the controller that is a java script code and want to init a variable of java script file with this data as a string.
What I mean is:
Model.TrialScript is equal to the string of:
<script type="text/javascript">var j = new Date();</script>
(I got it from the DB)
and then, I want to do the next thing in my js file:
var TrialScript = '<%= Model.TrialScript %>';
The problem is that TrialScript is not like I expect:
var TrialScript = '<script type="text/javascript">var j = new Date();
assuming I must get the js code as: <script type="text/javascript"> and not:
<script type=\"text/javascript\">, how can I solve this issue?
Another thing may helps: I want to run this script only when the user press a button (is called: button1)
Maybe is there an option to call this script from the js after the button is clicked without saving this script as a variable?
any help appreciated!
You can try that way:
var TrialScript = '<%= Model.TrialScript %>';
//remove script tags, get only the code
TrialScript = TrialScript.replace(new RegExp("^<script.*?>(.*)</script>"), "$1");
// transform the code as a JS function
TrialScript = new Function(TrialScript);
// associate to the button1
document.getElementById("button1").onclick = TrialScript;
This is very odd and illogical. I serve an html file using the django code below. The javascript code works if pn is an integer, ex. 612, but fails if it is a string, ex. U612. What the heck?
Django views.py:
context = {'pattoload' : str(pn)}
t = TemplateResponse(request, 'viewer/index.html', context)
t.render()
return t
Javascript index.html:
window.onload=function(){
var pn = String({{pattoload}});
alert(pn);
}
Ok the answer is as follows in javascript:
var pn = "{{pattoload}}";
This was not obvious to me and I am glad to have stumbled across it.
Looking for an elegant way of having scripts added once on a page and that's it.
I have a partial view that requires 2 CSS files and 2 JS files. In most places, there is only need for 1 of the partial views. On a single page though, I need 3 of these same partial views, and each partial view has the 4 files, so I have 6 JS links and 6 CSS links. Quite ugly.
I original idea was to use jQuery to see if the tags (by id) are existant on the page yet or not. If they aren't, then add them in. Otherwise, do nothing. This was going to be an inline script like....
<script type="text/javascript" language="javascript">
function(){
var jQueryUICSS = $("#jQueryUICSS");
if(!jQueryUICSS){
document.write('link id="jQueryUICSS" href="/Content/smoothness/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css" />')
}
...And so on for the other 3 tags.
};
But, I'm not sure that will work (or will the lead dev accept it):P
Any other ideas?
David,
I use a couple of static htmlhelpers in my code for exactly this scenario. it works on the principle that the context.items collection gets populated per request and therefore if an item exists in the context.items collection then it doesn't get added twice. anyway, enough of the scottish words of wisdOOOm, 'yill jist be waantin the coade'...
for our Scripts:
public static MvcHtmlString Script(this HtmlHelper html, string path)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
HttpContextBase context = html.ViewContext.HttpContext;
// don't add the file if it's already there
if (context.Items.Contains(filePath))
return MvcHtmlString.Create("");
// add the beast...
context.Items.Add(filePath, filePath);
return MvcHtmlString.Create(
string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", filePath));
}
for our cuddly css:
// standard method - renders as defined in as(cp)x file
public static MvcHtmlString Css(this HtmlHelper html, string path)
{
return html.Css(path, false);
}
// override - to allow javascript to put css in head
public static MvcHtmlString Css(this HtmlHelper html,
string path,
bool renderAsAjax)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
HttpContextBase context = html.ViewContext.HttpContext;
// don't add the file if it's already there
if (context.Items.Contains(filePath))
return null;
// otherwise, add it to the context and put on page
// this of course only works for items going in via the current
// request and by this method
context.Items.Add(filePath, filePath);
// js and css function strings
const string jsHead = "<script type='text/javascript'>";
const string jsFoot = "</script>";
const string jsFunctionStt = "$(function(){";
const string jsFunctionEnd = "});";
string linkText = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"></link>", filePath);
string jsBody = string.Format("$('head').prepend('{0}');", linkText);
var sb = new StringBuilder();
if (renderAsAjax)
{
// join it all up now
sb.Append(jsHead);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionStt);
sb.AppendFormat("\r\n\t\t");
sb.Append(jsBody);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionEnd);
sb.AppendFormat("\r\n");
sb.Append(jsFoot);
}
else
{
sb.Append(linkText);
}
return MvcHtmlString.Create( sb.ToString());
}
usage in both cases:
<%=Html.Css("~/Content/Site.Css")%>
<%=Html.Script("~/Scripts/default.js")%>
have fun...
[edit] - pay particular attn to the comment line:
// this of course only works for items going in via the current
// request and by this method
Put them in your master. CSS and Javascript files are cached. Load once and don't worry about it.