I have a Java list whose values I need to display in Javascript.
Here is my Java code to populate the List:
List<CoordinateVO> coordinateList = new ArrayList<CoordinateVO>();
for (Iterator iterator2 = cordinates.iterator(); iterator2.hasNext();) {
Adcoordinate object = (Adcoordinate) iterator2.next();
if(object!=null){
CoordinateVO co = new CoordinateVO(object.getLatitude(),object.getLongitude());
coordinateList.add(co);
}
}
Now I want to display values of CoordinateList in Javascript Dialog Box.
Is there any way out to do this ?
Finally I found the solution ,
I converted the java.util.List into Json Array in java code and then in Javascript I parse the Json Array .
Here is my Java Code
String json = new Gson().toJson(coordinateList); // List Conversion to Json Array
dataVO.setCoordinateArray(json);
In Javascript
<script>
var myObject=JSON.parse(dataVO.adScript);
var index;
for (index = 0; index < myObject.length; ++index) {
alert("Test Latitude "+myObject[index].latitude);
alert("Test Longitude "+myObject[index].longitude);
}
</script>
Related
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))');
Suppose I have a text file that I want to convert into json file. Precisely, I want to convert each line $line to "$line":"someid" . Is there a proper way to do that using bash script langage or javascript.
For example
I want to
convert
text into
json
would output
{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}
You can't do your expected output like that because you will produce a syntax error, but you can put multiple objects in an array instead. Something like this:
HTML
<div id="id">
I want to
convert
text into
json
</div>
JS
var textArr = document.querySelector('#id').innerHTML.split('\n');
function produceJSON(textArr) {
var arr = [];
// we loop from 1 to 1 less than the length because
// the first two elements are empty due to the way the split worked
for (var i = 1, l = text.length - 1; i < l; i++) {
var obj = {};
obj[text[i]] = i;
arr.push(obj);
}
return JSON.stringify(arr);
}
var json = produceJSON(textArr);
DEMO
I have following json data coming from server in which i want to extract LimitClass and LimitClassID and store their values in respective arrays.
{
"ErrorDesc":"",
"ErrorCode":"",
"LimitClassList":"[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]"
}
Here is the code I have tried :
var list = data.LimitClassList;
var arrayLimitClass = [];
var arrayLimitClassId = [];
for(var i in list) {
arrayLimitClass.push(list[i].LimitClass);
arrayLimitClassId.push( list[i].LimitClassId);
}
alert(list);
alert(arrayLimitClass);
alert(arrayLimitClassId);
List variable has following result when I alert it:
[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]
But I am getting dots (.) when I alert arrayLimitClass and arrayLimitClassId. What am I doing wrong in extracting rows of json Object?
"LimitClassList":"[{\"LimitClass\":\"L1....]"
^ ^
LimitClassList is a string, not an array. Make it so it is an actual array, than your code should work. There should be no reason to have to parse it again.
The value below data.LimitClassList is itself a String containing JSON. You have to decode this first.
var list = JSON.parse( data.LimitClassList );
var arrayLimitClass = [];
var arrayLimitClassId = [];
// ...
This is more or less a workaround. You should have a look at your server code and fix the encoding error there!
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.