First of all, sorry for bringing a question that has been answered so many times, but I have tried most of the procedures mentioned and still can't get it working.
I have an ASP.NET app (server-side), and I would like to visualize some results by using WebGL (JavaScript, client-side). I am able to create the canvas in aspx file and to draw a 3D object (a cube) by writing ALL the necessary JS code in a jscript file (As long as I know what I want to draw in advance, and writing all that in Jscript). However, my intention is to write a different object depending on my server-side code. When I click a visualize button, a postback is triggered. In the server some code is executed, and some coordinates are returned in an array, defined global in the aspx.cs file. I would need to pass that array of node coordinates from the server to the JS file in order to draw actually the object I want.
Here is basically what I have tried:
The easiest way I have found to pass a variable is to declare a property public in aspx.cs (c# code) and then in JS writing:
var clientVariable = '<%=ServerVariable%>';
I have tried this not with an array, but just with a string variable and if writing:
alert(clientVariable);
I see "<%=ServerVariable%>" in the window, NOT the actual value. I don´t know if I need any additional library or what. If I can't even get this easy example working, I don't know how I would even do it with a double array. I´m using MCVS08, ASP.NET 3.5 with HTML5.
Apart from that, I have tried to convert the array not with JSON, but with:
Page.ClientScript.RegisterArrayDeclaration();
I've used ClientScript.RegisterStartupScript(GetType(), "alert", "test2('" + A + "');", true);
I've tried to use a hidden block to store the session value, etc.
So basically, summing Up, I would like to have:
server-side: after executing a function of the code behind in the server, when rendering the page again I will have a global variable in aspx.cs which is a double[,] coordinates, containing the coordinates of nodes that will define the 3D object.
aspx: in html (not asp.net) I have a canvas tag in which I intend to have the visualization. The script that will render the image client-side is stored in a JScript file. In this file, inside a function I have a variable var vertices = []; which I need to feed with the values I got from the server in coordinates array. I don't know how to achieve this the best way. Would you recommend to use AJAX?
Any suggestion/comment would be very appreciated. As the dummy example with a simple string is not working (forgetting about canvas, webGL and all that stuff), may I need anything else or am I misunderstanding how to do it properly?
When I need to pass variables into JavaScript I usually I prefer var clientVariable = '<%=ServerVariable%>'; solution. This method is sufficient for small number of scalar variables. If you need to pass a complex object or a array, consider to use JavaScriptSerizlizer.
The behavior you are having it might happen for number of reasons. One of them might occur, if you have included a scriptlet into .js file, and not into .aspx file.
Here is how I would do this:
webgl-draw-file.js:
window.WebGlDraw = function(points /* point array */)
{
// Draw points here
}
Page1.aspx.cs:
public string GetSerializedServerVariable()
{
new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ServerVariable);
}
Page1.aspx:
<html>
<header>
<script src="webgl-draw-file.js"/>
<script type=text/javascript>
window.WebGlDraw(<%=this.GetSerializedServerVariable()%>);
</script>
</header>
<body>
...
</body>
</html>
To understand a better what values are passed to the JS function, take a look at a page source using your browser. You should see a JSON representation of your array instead of <%=Page.GetSerializedServerVariable()%> scriptlet.
It should look something like this:
<html>
<header>
<script src="webgl-draw-file.js"/>
<script type=text/javascript>
window.WebGlDraw([{x:1, y:2}, {x:1, y:2}, {x:1, y:2}, {x:1, y:2}]);
</script>
</header>
<body>
...
</body>
</html>
can u serialize the data like this:
<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var doublearr = <%= serializer.Serialize(ServerVariable) %>;
Related
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
There is some data that I need to get from a local crawled page. It's inline javascript like this:
<script type="text/javascript">
//<![CDATA[
var graph_data = {"query":{"cid":["13908"],"timestamp_from":1402531200,"timestamp_till":1402531200,"views":1138942,"data":
etc, the variable is very long but you get the idea. I want to put "graph_data" into an array called $data. What is the best way to do this? I should add this is all being done by me locally & I don't need to execute any javascript code, just extract the data.
I have make a suggestion purely as an idea with some code worth trying!
As suggested, the DOM Document may provide this much easier, but here's another possible solution for extracting...
I'm guessing that the var graph_data is a JSON string that you want to extract from the HTML page so that you can store as a PHP var. The problem is that your code doesn't show how the variable ends but I'm going to assume that a new line break would be the way to identify the end of the variable being set. It may be a semi-colon though and if it is, instead of "\r\n" try ";"
// Assuming your html code is stored in $html...
preg_match("/var graph_data[^\{]*?(\{[^\r\n]+?)/is",$html,$match);
print "<pre>";
print_r($match);
print "</pre>";
This should result in $match[1] storing the part you need.
You can try passing that into json_decode() but that's touching some wood with crossed fingers.
Good luck...
I have googled it several times but i can't get a solution. I want to make javascript function call from the bean class in jsf and i get that using the following code.
RequestContext.getCurrentInstance().execute("handleResize()");
and is workign fine. But I want to give two parameters to that function height and width. How can it be done ? please help
You seem to fail to grasp the fact that in the context of Java/JSF, all the HTML, CSS and JavaScript code are merely plain vanilla Strings and you seem to expect that HTML/CSS/JS somehow magically runs inside Java/JSF code. This is not true. Java/JSF is a HTML/CSS/JS code producer, not executor. The webbrowser retrieves them all as one big String and then parses and executes it.
If you want to invoke a JS function with parameters supplied, like so when you would do in real JS code:
handleResize(500, 300);
And you have those values as Java variables, then you just need to make sure that you write Java code in such way that exactly the above String is produced (again, this is just Java code, no JS code):
String call = "handleResize(" + w + ", " + h + ")";
You can verify beforehand by printing it to the stdout/logger:
System.out.println(call);
It must print exactly the desired valid JS function call syntax handleResize(500, 300);.
If it does, then just pass that unmodified to RequestContext#execute().
RequestContext.getCurrentInstance().execute(call);
I have a bean and want to iterate through the values and store it in an array.
My form bean name is keywords and the element to be accessed is keywordList, so in my JS when I alert("${keywords.keywordList}");
I get [com.test.bean.Keyword#10, com.test.bean.Keyword#f, com.test.bean.Keyword#e], but I want the values and assign them to a var, how can I do this?
javascript and java are two different languages, you can not assume that you pass the keywords.keywordList in java and get the corresponding objects in javascript, you need to iterate the keywordlist in java and create the corresponding javascript objects manually.
update: some pseudocode
out.print("var keywordsInJS = []")
for (String keyword : keywordList) {
out.print("var keyword = '" + keyword + "';");
out.print("keywordsInJS.push(keyword);");
}
// now you can use keywordsInJS in js.
Here is how I solved my problem
<script>
var i = 0;
var collection = new Array();
</script>
And since I was using logic:iterator and displaying the values in the table, I added
<script>
collection[i++] = "${keyword.name}";
</script>
Now when I alert collection, all the words are in the array. Which is exactly what I need.
This is what I have done to solve this issue on JSP page
< %# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script type="text/javascript">
var keyWordsArray=new Array();
var rowCounter=0;
<c:forEach items="${keywords.keywordList}" var="keyWords">
var fieldObj=new Object();
fieldObj.value='<c:out value="${keyWords}"/>'
keyWordsArray[rowCounter]=fieldObj;
rowCounter++;
</c:forEach>
</script>
</code>
Now you can access keWordArray in Javascript.
In my experience JS and Java doesn't interact well...
I suggest you to use HTML as a middle term for them to interact. Like, for example, displaying the contents of the list in invisible text in html (with iterator and the property indexed you can have different names for each text), then you can get them in JS.
You should also keep the length of the list so when you iterate in JS you know when to stop.
I know this far from a perfect solution and far from something remotely nice to do. But I know no better way to do it :(
Hope there is one, so I can also use it :)
I have a Grails variable which is of type JASONList that is rendered in a template.
Is there a way to access this list from inside a JavaScript function?
Let's say I want onresize to fit all the objects on the screen. Without making a database call and refetching the entire list from Ajax...
Let's say the template does something like this:
<g:each var="report" in="${reportList?.myArrayList}">
<li style="display:inline; list-style:none;">
<img src=" ${report?.img}">
</li>
</g:each>
<script type="text/javascript">
function resize(list) {
if (list.size <givenSize) // Pseudocode
list.subList() // Pseudocode
}
window.onresize = resize("${reportList}")
</script>
The problem with this is that for some reason Grails gsp does not render "${reportList}" as a list. Instead it renders it as the string "${reportList}".
I am probably thinking of this problem completely wrong, but is there a way to resize these objects or get them through document.getElementById or something of that nature?
The $reportList is populated by POJO as JSON conversion...
Grails variables only exist on the server side. JavaScript runs in the browser (client side). Everything that's sent to the browser is a string, so while you can use Grails to generate a piece of JavaScript like window.onresize = resize("${reportList}"), the browser will only see the string that ${reportList} evaluates to.
That means that, if you use Grails to pass a variable to the resize() JavaScript function, the parameter (list) will only ever be a string - you won't be able to access server-side list methods like list.size or list.subList(), because the list variable is no longer a list; it's just a string.
I don't know, but maybe Grails doesn't want to evaluate expressions inside script tags. Dynamically generated scripts is not a very good practice.
But until you find the exact cause, you could try something like this:
<g:each var="report" in="${reportList?.myArrayList}">
<li style="display:inline; list-style:none;">
<img src=" ${report?.img}">
</li>
</g:each>
<%= """<script type=\"text/javascript\">
function resize(list){
if(list.size <givenSize) //posudo code
list.subList() // psudocode
}
window.onresize = resize(\"$reportList\")
</script>""" %>
I'm not sure why your ${reportList} is being rendered as ${reportList}, because when I do the following:
var t = "${taskList}";
I get the following in my HTML:
var t = "[com.wbr.highbar.Task : 1, com.wbr.highbar.Task : 4, com.wbr.highbar.Task : 2, com.wbr.highbar.Task : 5]";
That said, you're still going to have issues, because JavaScript will have no idea what to do with your reportList. If it is pure JSON, you would need to eval() it so that it gets turned into a JavaScript Object.
I figured out my problem. Basically if you are using POJO in Grails the Grails as JSON conversion is not very smart. All it does is a toString on the object instead of potentially looking at all the public accessors, etc.
It is kind of disappointing, but basically I need to create the JSON conversion in the toString method of my POJO.