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.
Related
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.
I'm passing a List from my controller to a view, where I want to be able to take the Model and loop through results in JQuery/Javascript. I'm having a heck of a time figuring out how to do that.
My controller returns a list of colors. In the view, I converted the List to an array. I then pass it to my where I'm trying to loop through it to build an array I can using in my JS.
<script>
$(document).ready(function () {
var currentView = sessionStorage.getItem('lastView');
var jsArr;
for (i=0; i<#arr.Length; i++) {
jsArr.push(#arr[i])
}
if (!currentView) {
sessionStorage.setItem('lastView', 0);
$("body").css("background-image", "url('/Images/Home/#arr[0].Location')");
} else {
sessionStorage.setItem('lastView', currentView++);
}
})
</script>
There has to be an easy way of doing this...
<script>
$(document).ready(function () {
var currentView = sessionStorage.getItem('lastView');
var jsArr = #Html.Raw(Json.Encode(arr)) ;
if (!currentView) {
sessionStorage.setItem('lastView', 0);
$("body").css("background-image", "url('/Images/Home/#Html.Raw(arr[0].Location)')");
} else {
sessionStorage.setItem('lastView', currentView++);
}
})
</script>
I would instead return json from the server. However if you want to do it in an html view I think something like this might work:
var jsonObj = '#Html.Raw(Json.Encode(Model.arr))'
//the loop is unnecessary, but can be useful if you need additional processing
var myArray = [];
for (i=0; i<jsonObj.length; i++) {
myArray.push(jsonObj[i])
}
Here is a way to manually build a JSON or JS object with razor code, some very easy to use code:
#foreach (var item in Model.Users)
{
<text>
UserData[UserData.length] = {
"UserID": '#item.ID', "FullName": '#item.Name'
};
</text>
}
I purposefully showed model property names being used and JSON property names being different to show an advantage of manually building the array.
Also, in this case you would be able to send a model through with multiple collections of data. Then just iterate through that collection (#foreach (var item in Model.Users)) with your Razor code to build your JSON or Javascript object array
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))');
This is the code I have
<script>
function validation () {
var x=document.getElementById("user").value;
var y=document.getElementById("user");
var names="<%=names%>";
for (var j=0; j<names.length; j++) {
if (names[j].test(x)) {
//alert(names[j].match(x));
return true;
}
else{
y.focus();
return false;
}
}
}
</script>
This is for a login page,2 fields are there as usual username password.
I am checking if the username is there in the database,he can enter the password or else he cant.But this code doesnt go to the password even if the username is right.
What am I doing wrong?
Suppose the data type of names in java is an String[], the code <%=names%> equals to <%=names.toString()%>.
So when the jsp is rendered, your javascript code will be something like var names="[Ljava.lang.String;#5d888759". Obviously, it not a valid javascript array definition.
Your need to process your java array first. Add the following code to your jsp(above your javascript code):
<%
StringBuilder sb = new StringBuilder();
sb.append("[");
for(String name : names) {
sb.append("'");
sb.append(name);
sb.append("',");
}
if(sb.charAt(sb.length() - 1) == ',') {
sb.setLength(sb.length() - 1); //remove tailing ','
}
sb.append("]");
String strNames = sb.toString();
%>
And then modify your js code to:
var names="<%=strNames%>";
After jsp rendered, your js code will be like:
var names="['foo','bar']";
which is a valid array definition in js. Then it will work.
If the data type of names in java is List<String>, the solution is similar.
I have found the answer.Thnx for the help
this is the answer
function validation() {
var x=document.getElementById("user").value;
var y=document.getElementById("user");
var z=document.getElementById("pass");
var names="<%=names%>";
names= names.replace("[", "").replace("]", "");
names=names.split(", ");
for (var j=0; j<names.length; j++) {
if (names[j].localeCompare(x)==0) {
return true;
}
z.removeAttribute("readonly", 0);
}
alert("You username is not registered on our databsae");
y.focus();
}
check this out
CASE 1
var names='{id:1,key:"Apple"}'; // here names is string
names.key // will give you error
// so you need to parse it
//using the json2.js script:
var obj = JSON.parse(names);
obj.key // will give you Apple
var obj = jQuery.parseJSON(names)// in jquery
Newer browsers support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.
CASE 2
var names={id:1,key:"Apple"}; // here names is object
names.key // will give you Apple
REFERENCE
JSON = > https://github.com/douglascrockford/JSON-js
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