This is a code written in a.jsp:
<script type="text/javascript" >
function chk(d,e)
{
var x = d.split('/')
var y = e.split('/')
var a = new Date(x[2],x[0],x[1])
var b = new Date(y[2],y[0],y[1])
var c = ( b - a )
var p= c / (1000 * 60 * 60 * 24);
}
</script>
<% String b="2013/07/12";
String c="2013/07/14";%>
<script>
var myVar=chk('$b','$c');
</script>
<body>
<% String st="<script>document.writeln(myVar)</script>";
out.println("value="+st); %>
</body>
I want to get the number of days(i.e. 'p') between these 2 dates(i.e. 'b' and 'c') as the output. But the output I am getting is "value=NaN". What is wrong with this code? Please help.
This question was tricky to answer. First, looks like you want to pass the variables declared in scriptlet to your JavaScript using EL. To accomplish this, you should:
Set the variable in scriptlet as pageContext attribute or request attribute as explained here: How to evaluate a scriptlet variable in EL?
Use JSTL <c:out> to send the variable from EL to your JavaScript function.
Following GauravSharma's answer suggestion, add a return p; at the end of your JavaScript function.
Your code should look like this (at least works for me using Tomcat 7 and prints 2 in the navigator):
<script type="text/javascript">
function chk(d, e) {
var x = d.split('/');
var y = e.split('/');
var a = new Date(x[0], x[1] - 1, x[2]);
var b = new Date(y[0], y[1] - 1, y[2]);
var c = (b - a);
var p = c / (1000 * 60 * 60 * 24);
return p;
}
</script>
<%
String b = "2013/07/12";
String c = "2013/07/14";
pageContext.setAttribute("b", b);
pageContext.setAttribute("c", c);
%>
<script>
var myVar = chk('<c:out value="${b}" />', '<c:out value="${c}" />');
</script>
<body>
<%
String st = "<script>document.writeln(myVar)</script>";
out.println("value=" + st);
%>
</body>
As said in my comment on your question, this looks like an exercise for practicing about scriptlets, EL, JSTL and JavaScript integration. This kind of code is not meant to be used in a live production system NEVER. Scriptlets usage is discouraged since long time. Refer to: How to avoid Java code in JSP files?. Also, show this to your teacher, professor or whoever is teaching you about Java web development.
At the end of the function, add return p;.
Your function didn't returned anything that's why undefined was written on screen.
function chk(d,e)
{
var x = d.split('/')
var y = e.split('/')
var a = new Date(x[2],x[0],x[1])
var b = new Date(y[2],y[0],y[1])
var c = ( b - a )
var p= c / (1000 * 60 * 60 * 24);
return p;
}
Simply call write this
var myVar=chk('$b','$c');
on document ready.
Because JSP just written the script to document.Not executed yet.
Related
I want to parse a Custom Search Element JavaScript function.
Here's a template of this function https://developers.google.com/custom-search/docs/element#overview.
<!-- Put the following javascript before the closing tag. -->
<script>
(function() {
var cx = '123:456'; // Insert your own Custom Search engine ID here
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>
<!-- Place this tag where you want both of the search box and the search results to render -->
<gcse:search></gcse:search>
I want to parse this function from this site http://findmusicbylyrics.com/search.php?cx=partner-pub-1936238606905173%3A1893984547&cof=FORID%3A10&ie=UTF-8&q=Love&sa=Search+Lyrics which it's JavaScript is:
<script>
(function() {
var cx = 'partner-pub-1936238606905173:8242090140';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'http://www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>
Now i have no idea of where to start with it. I've done some HTML parsing using java Jsoup but this is the first time i bump into this CSE <script> tag to parse.
Any suggestions will be very appreciated.
I've done some HTML parsing using java Jsoup but this is the first time i bump into this CSE tag to parse.
You'll fetch the page and then find the script element. Once done, you'll call the html() method on this element.
HELPER FUNCTION
/**
*
* Extract the Custom Search Element JavaScript of a site.
*
* #param url
* The site url
* #param cssQuery
* The query for finding the script element
* #return the content of the between the tags <script> and </script>
* #throws IOException
* If the CSE Javscript is not found or an error occured during
* {#code url} fetching.
*
*/
public static String getCustomSearchElementJavascript(String url, String cssQuery) throws IOException {
Document doc = Jsoup.connect(url).get();
Element script = doc.select(cssQuery).first();
if (script == null) {
throw new IOException("Unable to find Custom Search Element JavaScript.");
}
return script.html();
}
SAMPLE CODE
String url = "http://findmusicbylyrics.com/search.php?cx=partner-pub-1936238606905173%3A1893984547&cof=FORID%3A10&ie=UTF-8&q=Love&sa=Search+Lyrics+";
System.out.println( getCustomSearchElementJavascript(url, "div#content > script") );
OUTPUT
(function() {
var cx = 'partner-pub-1936238606905173:8242090140';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'http://www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
I am attempting to write an example JSP page for myself (very new to jsp), and have gone over an example to write one, but how do I get time to consistently update?
here is my snippet of code:
<body>
<%
java.text.DateFormat df = new java.text.SimpleDateFormat(
"HH:mm:ss:SS z MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
%>
<h1>
Current Date and Time:
<%=df.format(cal.getTime())%>
</h1>
</body>
By the way i'm using a tomcat server to deploy this
function updateYourTime() {
var now = new Date(),
months = ['January', 'February', '...'];
time = now.getHours() + ':' + now.getMinutes(),
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
document.getElementById('currentTime').innerHTML = [date, time].join(' / ');
setTimeout(updateYourTime, 1000);//This method will call for every second
}
updateYourTime(); // initial call
see here for details
<div id="currentTime"></time>
do you mean to show clock in your pages?
you can use java script.
here is an example
to show server clock in clients jsp use this javascripcode with java
Add a label where ever you want to show the server Time
<strong>Server Time : </strong><label id="timelable"></label>
And then add the following java script code at the end of the jsp inside the body tag
<script type="text/javascript">
var myVar = setInterval(function(){ myTimer() }, 1000);
var jsVar= <%=java.util.Calendar.getInstance().getTimeInMillis()%>;
var timeZoneOffset=<%=java.util.TimeZone.getDefault().getOffset(System.currentTimeMillis())%>;
jsVar=jsVar+timeZoneOffset;
function myTimer() {
jsVar=jsVar+1000;
var d = new Date(jsVar);
var t=d.toUTCString();
document.getElementById("timelable").innerHTML = t;
}
</script>
Thats it now you will see the server time running in you jsp.
I am trying to create a form using java script, the form is created but the dynamic param values to the form are not replaced. The following is my form....
var formVar='<form:form name="service_form" commandName="command1" action="/serviceProcess" method="post">';
formVar+='<label for="'+ paramsdata[2] + '">'+paramsdata[3]+'</label><br/>';
formVar+='<form:input type='+paramsdata[2]+' path="webParamMap['+paramsdata[2]+'].webValue" value='+ paramsdata[5] +' class="input"></form:input><br>' ;
formVar+='<label for=" '+paramsdata[2]+' ">'+paramsdata[3]+'</label><br/>';
formVar+='<div id="select">';
formVar+='<form:select path="webParamMap[' +paramsdata[2] + '].webValue">';
formVar+='<form:option value='+paramdata[8]+'>'+paramdata[9]+'</form:option>';
formVar+='</form:select></div>';
formVar+='</form:form>';
In the above form the label tag values(dynamic param values) are updated but the form:input and select tag values(dynamic param values) are not updated in the output.
please help me how to create these tags with dynamic parameters ?
JAVA != JAVASCRIPT
Notice:
<form:form>
This is server-side Java.
Your Javascript is client-side only.
With following script each element is getting its right value. I wonder why are you using "
<script>
var paramsdata = new Array();;
paramsdata[2]='param2';
paramsdata[3]='param3';
paramsdata[5]='param5';
paramsdata[8]='param8';
paramsdata[9]='param9';
var formVar='<form:form name="service_form" commandName="command1" action="/serviceProcess" method="post">';
formVar+='<label for="'+ paramsdata[2] + '">'+paramsdata[3]+'</label><br/>';
formVar+='<form:input type='+paramsdata[2]+' path="webParamMap['+paramsdata[2]+'].webValue" value='+ paramsdata[5] +' class="input"></form:input><br>' ;
formVar+='<label for=" '+paramsdata[2]+' ">'+paramsdata[3]+'</label><br/>';
formVar+='<div id="select">';
formVar+='<form:select path="webParamMap[' +paramsdata[2] + '].webValue">';
formVar+='<form:option value='+paramsdata[8]+'>'+paramsdata[9]+'</form:option>';
formVar+='</form:select></div>';
formVar+='</form:form>';
document.body.innerHTML = formVar;
</script>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue){
var newElement = document.createElement("<input name='"+elementName+"' type='hidden'>");
inputForm.appendChild(newElement);
newElement.value = elementValue;
return newElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
createNewFormElement(submitForm, "field1", "somevalue");
createNewFormElement(submitForm, "field2", "somevalue");
submitForm.action= "someURL";
submitForm.submit();
}
</script>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()">
I'm making a website containing a book and the user should have the option to go to the next or previous chapter. Each chapter has 1 html file. I'm already using this script, but when I press the next or previous button, enter link description here tries to load this page rather than 2.html
<script type="text/javascript">
function goto(url) { window.location=url; }
var curPage = parseInt(location.href.replace(/([1-93]+)\.html/, ''))
if (curPage <= 1) {
// First page, no 'back' link
document.write('Back');
} else {
var backPage = curPage-1;
document.write("Back");
}
if (curPage >= 93) { // Replace with highest page number
// Last page, no 'next' link
document.write('Next');
} else {
var nextPage = curPage+1;
document.write("Next");
}
</script>
can you use jQuery to do something of this nature?
$('#next').click(function(e)
{
e.preventDefault()
$('#currentPage).remove();
$(#'yourDiv').load('2.html, function()
{
//more logic here
});
});
So firstly you make a directory lets say:
localhost/book/
Secondly add a few html documents in that directory (such as 1.html, 2.html, 3.html) paste in the following html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script src="code.js"></script>
<a class="prev" href="#">Load Prev page</a>
<a class="next" href="#">Load Next page</a>
Create a javascript file called code.js in the root directory and paste the following code:
$(function(){
var _href = location.pathname.split('/')[1];
var _url = location.pathname.split('/');
var _length = _url.length;
var _page = _url[_length - 1] + "";
var _current = _page.split('.')[0];
_current = parseInt(_current);
$('a.next').click(function(){
var request = location.protocol + '//' + location.hostname + '/' + _href + "/" + (_current + 1) + '.html';
$.ajax({
url: request,
type:'HEAD',
error: function()
{
// last page
},
success: function()
{
window.location = request;
}
});
});
});
Your problem is probably with your curPage variable. Try this:
curPage = location.href.substring(location.href.lastIndexOf('/') + 1);
curPage = parseInt(curPage.replace(/([1-99]+)\.html/, '$1'));
I believe your replace function is replacing everything with an empty string. This should replace the page with the number.
Updated
See code above. You need to get the page name from the URL before you use the replace function.
Forgot to put location.href in the first line.
I have a Java applet.
After user inputs data into the Java applet controls he presses button in Java applet and Java applet performs some calculating and result is a table (for simplicity table can be considered as String[][]).
I want to show new browser window and output this table in it as html <table>.
How can this be done?
Preferred way is to use javascript if needed, but not involving some server side handling.
Well, JavaScript will have to be used to open the window and populate the HTML - this is something the applet simply has no access to.
Luckily, JavaScript can easily call any public methods your Java applet provides. Unfortunately, Java cannot return a String[][] to JavaScript, but it CAN return a String.
So what you can do is have your Java applet return a JSON serialization of your String[][] array. JavaScript can then convert that JSON to a JavaScript array using the JSON.parse function (available on most modern browsers, but there are also libaries available at json.org)
So here's an example of what I am talking about (that works with at least Java 5 and Chrome):
The Applet Code
import java.applet.*;
public class Test extends Applet {
String data[][];
public void init() {
data = new String[5][2];
data[0] = new String[] { "Peter", "Griffin"};
data[1] = new String[] { "Glen", "Quagmire"};
data[2] = new String[] { "Joe", "Something"};
data[3] = new String[] { "Cleveland", "Brown"};
data[4] = new String[] { "Buzz", "Killington"};
}
public String getData() {
return toJSON(data);
}
/* Quick and dirty, you may want to look
* online for a 'complete' converter
*
* This returns [["Peter", "Griffin"], ["Glen", "Quagmire"], ... etc
*/
protected String toJSON(String data[][]) {
int x, y;
String s = "[";
for (y = 0;y < data.length;y += 1) {
s += "[";
for (x = 0;x < data[y].length;x += 1) {
s += "\""+data[y][x].replaceAll("\"","\\\"")+"\"";
if (x < data[y].length-1) {
s += ", ";
}
}
s += "]";
if (y < data.length-1) {
s += ", ";
}
}
s += "]";
return s;
}
}
The JavaScript Code
<html>
<body>
<p><applet id="applet" code="Test"></applet></p>
<input id="button" type="button" value="Click me"/>
<script type="text/javascript">
(function () {
var button = document.getElementById("button"), applet = document.getElementById("applet");
button.onclick = function () {
var html = [], newWindow, data = JSON.parse(applet.getData()), j;
html.push("<table><tr><th>First Name</th><th>Last Name</th></tr>");
for (j = 0;j < data.length;j += 1) {
html.push("<tr><td>"+data[j][0]+"</td><td>"+data[j][1]+"</td></tr>");
}
html.push("</table>");
newWindow = window.open();
newWindow.document.firstChild.innerHTML = html.join("");
};
}());
</script>
Let me know if you need further clarification!
Preferred way is to use javascript if needed, but not involving some server side handling.
If you really must not have any server side interaction, it'll have to be a jQuery hide/show situation.
If you can bear some server side work, do it with an applet collaborating with servlet. The applet won't do the calculation; the servlet will. After it's complete, the servlet adds the result to the output page and redirects the output stream to it.