How can we get JavaScript array by JSP scriptlet - javascript

I need JavaScript array/multidimensional which is returned by Java class,
<script type="text/javascript">
var strComboValue = <%=DBComboOptions.getOptions(combos)%>;
</script>
Here, strComboValue is a JavaScript variable and the DBComboOptions.getOptions(combos) returns array in Java class. Now I want that array in JavaScript.

Just let Java/JSP print a syntactically valid JS array syntax. Keep in mind that Java/JSP and JavaScript doesn't run in sync. Java/JSP produces HTML as one large String and JS is just part of it. JS ultimately runs in the webbrowser once it has retrieved all that HTML output from Java/JSP.
Assuming that you ultimately want the following valid JS array syntax:
<script type="text/javascript">
var strComboValue = [ "one", "two", "three" ];
</script>
Then you should write your Java/JSP code accordingly so that it prints exactly that syntax:
<script type="text/javascript">
var strComboValue = [
<%
String[] options = DBComboOptions.getOptions(combos);
for (int i = 0; i < options.length; i++) {
%>
"<%= options[i] %>"
<%
if (i + 1 < options.length) {
%>
,
<%
}
}
%>
];
</script>
It's only terribly unreadable (and not only because of using old fashioned scriptlets instead of taglibs). Easier, however, is to grab a JSON (JavaScript Object Notation) library like Google Gson and create an additional method getOptionsAsJson() which does something like the following:
public getOptionsAsJson(Object value) {
return new Gson().toJson(getOptions(value));
}
And finally use it instead:
<script type="text/javascript">
var strComboValue = <%=DBComboOptions.getOptionsAsJson(combos)%>;
</script>

your can use json lib, on http://json.org there are many json librarys,
i.e.
int[] arr = new int [] {1,2,3}; // java
convert to:
var arr = [1,2,3]; // javascript

Related

How to create an array or object of variables by looking them in the DOM?

I am generating some JS variables on a Twig template and I am prefixing them with a dynamic value. For example:
<script type="text/javascript">
quoteGridId = 'grid_quote';
</script>
<script type="text/javascript">
quoteContactGridId = 'grid_quote_contact';
</script>
<script type="text/javascript">
archiveGridId = 'grid_archive';
</script>
I need to be able to use them in a Javascript file included after the page loads. How can I create an array of values containing all the *GridId vars?
I would like to be able to use the following on the script:
[
'quoteGridId' => 'grid_quote',
'quoteContactGridId' => 'grid_quote_contact',
'archiveGridId' => 'grid_archive',
]
UPDATE:
Let's try to get my problem clear for those ones opened to help. Currently I am working on a legacy system. Such system had a grid generating a gridId value and at the end a JS file was included and such file was using the var gridId to perform several things.
Now I need to replicate more than one grid on the same page and that becomes a problem since two grids are generating the same var name:
gridId = 'something';
gridId = 'something1';
When the script try to reach the gridId var is getting always the latest one (something1) and therefore no actions are being taken on the first grid.
My solution was to prefix the name to each gridId resulting on what I've as OP. Ex:
somethingGridId = 'something';
something1GridId = 'something1';
What I am trying to find is a way to re-use the main JS file by passing those dynamic gridIds but I can't find a way to get this to work.
The only solution I've in mind is to create the same file per grid and then change the value of gridId to the name of the ID to be used ....
I am open to ideas, any?
You can search the window variables with regex expressions (regular expression expressions?) i.e./.+GridId/ matches any word or variable that ends in GridId you can then iterate over them as you wish.
Example:
var pattern = /.+GridId/;
GridIds = []
for (var varName in window) {
if (pattern.test(varName)) {
GridIds.push({varName:window[varName]})
}
}
console.log(GridIds);
<script type="text/javascript">
quoteGridId = 'grid_quote';
</script>
<script type="text/javascript">
quoteContactGridId = 'grid_quote_contact';
</script>
<script type="text/javascript">
archiveGridId = 'grid_archive';
</script>
Hope this helps!
Instead of assigning quoteGridId = 'grid_quote', why don't you create a top level object and then assigning each var as a key-val pair, like:
var gridData = {}
gridData.quoteGridId = 'grid_quote'
gridData.quoteContactGridId = 'grid_quote_contact';
/* etc assignments */
//Access your data points like so in a loop, if you choose
Object.keys(gridData).forEach(key => {
const val = gridData[key]
//User `key`, and `val` however you'd like
})
i think you have you use List.
each time you push you value to the list like that :
var myList = [];
myList.push('something');
myList.push('something1');
now you cann access to all of them like that :
console.log(myList[0]);
console.log(myList[1]);
or just last :
console.log(myList[myList.length - 1])

How to represent a Java array in javascript of a Java Web Project?

Assume I have following code in a jsp file in JavaWeb:
<%
String myList = new String[10];
for(int i=0;i<10;i++){
myList[i] = String.valueOf(i);
}
%>
Now I want to get the value of the elements of myList in a loop of javascript:
Are the following ways are correct?
<script type="text/javascript">
var arr = new Array(10);
for(var i=0;i<10;i++){
arr[i] = "<%=myList[i]%>"
}
<script>
If not, how could I reach my purpose?
EDIT : Look at there Passing array from .jsp to javascript function
No, this isn't correct. Because the jsp i will never change.

How to get result from TSQL to JavaSCript using old classic ASP page?

We have a classic ASP page which has the below vbscript.
1) invoiceResult is a VB Array
2) invoiceSql: stored proc on SQL server
3) ricoh is company library which I cannot change (no access)
invoiceResult = ricoh.storedproc(invoiceSql)
Question: I need a javascript array instead of vb6. It does not matter how I get it. Can I somehow transform a vb6 array to a javascript array?
Or can I use Ajax to get SQL data from classic ASP?
You can access VBScript code from JavaScript. Somethin like this might work:
<SCRIPT LANGUAGE="VBSCRIPT">
Function makeArrayVB()
' Creates a VBScript array
dim anArray(1,1)
anArray(0,0) = "0,0"
anArray(0,1) = "0,1"
anArray(1,0) = "1,0"
anArray(1,1) = "1,1"
makeArrayVB = anArray
End Function
<SCRIPT LANGUAGE="JavaScript">
// Accesses a VBScript array within a JScript script
function getVBArray()
{
var arrayObj;
var jsArray;
arrayObj = makeArrayVB();
jsArray = VBArray(arrayObj).toArray();
alert("VBScript array length = " + jsArray.length);
// Displays the contents of the array
for(i=1;i<=jsArray.length;i++)
{
alert(jsArray[i-1]);
}
}
</SCRIPT>

Call JavaScript function with Razor syntax

I am currently working on an ASP.Net MVC application.
From my database, I have created three dictionaries and stored them inside a View Model.
After populating said dictionaries with some logic in the controller, I'm accessing these dictionaries in my View via #Model
After manipulating these dictionaries, I need to send the data to a JS function to apply some logic to a JS library called DHtmlxScheduler
I have read about the Razor syntax using #: and am currently using this method to send two string arrays. when trying to access these arrays in the JS function, they only appear to hold System.String[]
Here is the code:
var weekArray;
var engArray;
#foreach(var week in Model.WeeklySchedule)
{
var key = week.Key;
var values = week.Value.ToArray();
var eng = Model.EngineerSchedule.Where(k => k.Key == key).Select(v => v.Value).ToArray();
string test = "hello";
#: gatherTimes('#values', '#eng');
}
function gatherTimes(values, engs)
{
for(var i = 0; i < values.length; i++)
{
alert(values[i]);
}
//alert(values);
//alert(engs);
//weekArray[weekArray.length] = values;
//engArray[engArray.length] = engineers;
}
I eventually plan on looping through the arrays, they hold information about time slots and engineer IDs. If there is any more information I may provide, I will do my best to do so.
You will need to encode the list to JSON using JSON.Encode. Here is an example:
#{
// C# collection
var collection= new List<string> {"A", "B", "C"};
}
<script type="text/javascript">
// encode C# collection to JSON, set to javascript variable
var arr = #Html.Raw(Json.Encode(collection))
for(var i = 0; i < arr.length; i++)
{
console.log(arr[i]); // Output is A B C
}
</script>
In your case it would be like so:
#: gatherTimes('#Html.Raw(Json.Encode(values))', '#Html.Raw(Json.Encode(eng))');

accessing session variables in javascript inside jsp

I need to provide data for google APIs table... so I'll send it from servlet to JSP
but how can I access this data in "googles" javascript?
I'll provide sample of another JS - very simple one - just to let me learn how to make what topic says
<script>
function showTable()
{
<%
Object obj = session.getAttribute("list");
List<String> list = new ArrayList<String>();
int size = 0;
if (obj != null) {
list = (ArrayList<String>) obj;
size = (Integer) session.getAttribute("size");
}
for (int i = 0 ; i < size ; i++) {
String value = list.get(i);
%>
alert('<%= i %> = <%= value %> ');
<%
}
%>
}
</script>
It has to print elements of given list... but now it's just a big scriplet with alert inside of it... for to refactor it? I don't like having to much java in JSPs, because servlet is where it should be placed
EDIT: just to sum up - I would prefer "normal" JS for loop here... Generally I'd prefer to minimize java code, and maximize JS
Convert it to JSON in doGet() of a preprocessing servlet. You can use among others Google Gson for this. Assuming that you've a List<Person>:
List<Person> persons = createItSomehow();
String personsJson = new Gson().toJson(persons);
request.setAttribute("personsJson", personsJson);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
(note that I made it a request attribute instead of session attribute, you're free to change it, but I believe it doesn't necessarily need to be a session attribute as it does not represent sessionwide data)
Assign it to a JS variable in JSP as follows:
<script>
var persons = ${personsJson};
// ...
</script>
This way it's available as a fullworthy JS object. You could feed it straight to the Google API.
Now invoke the URL of the servlet instead of the JSP. For example, when it's mapped on an URL pattern of /persons, invoke it by http://localhost:8080/contextname/persons.
JavaScript is executed at client side, and scriptlets, EL, and JSP tags at server side. From the point of view of the server-side code, JavaScript is just generated text, just like HTML markup.
So, if you want to have a JavaScript loop which loops over a JavaScript array in the generated HTML page, you need to generate the JavaScript code which initializes the array, and the JavaScript loop.
Here's the JSP code
var theArray = [<c:forEach items="${sessionScope.list}" var="item" varStatus="loopStatus">'${item}' <c:if ${!loopStatus.last}>, </c:if></c:forEach>];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
This JSP code will generate the following JavaScript code, assuming the list in the session attribute contains "banana", "apple" and "orange":
var theArray = ['banana', 'apple', 'orange', ];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
Make sure, though, to properly escape the values of the list in order to generate valid JavaScript code. For example, if one of the values was "I'm cool", the generated JavaScript would be
var theArray = ['I'm cool', 'apple', 'orange', ];
which is not valid anymore. Use commons-lang StringEscapeUtils.escapeEcmaScript to escape the values.
since the ArrayList is having objects of Strings you can simply use split() method on the value of the array list. Something like as below;
function showTable() {
<%
Object obj = session.getAttribute("list");
List list = null;
if (obj != null) {
list = (ArrayList<String>) obj;
} else list = new ArrayList<String>(); %>
var jsList = <%=list.toString()%>
//remove [] from content
jsList = jsList.replace("[","");
jsList = jsList.replace("]","");
//split the contents
var splitContent = jsList.split(","); //an array of element
for(var i=0;i<splitContent.length;++i) {
alert(splitContent[i]);
}
}
I hope this will help you solve this.

Categories