Reading array from java servlet in javascript - javascript

Hi like the title says I am trying to read an array from my java Servlet. I am trying to read the array in my java script file.
Java servlet code:
String graphData[] = dbHandler.select(attributes); // filling the array with data from database.
request.setAttribute("graphData", graphData);
RequestDispatcher dispatcher = request.getRequestDispatcher("/displayData.jsp");
dispatcher.forward(request, response);
<script type="text/javascript">
var graphData = ['${graphData}'];
var graphData= pageContext.getAttribute("graphData");
var graphData = document.getElementById("graphData");
var GraphData = ['${graphData}'];
log("test: " + graphData);
</script>
I tried all those options but none of them worked.
Can someone please tell me what the correct way is to read an array from a java servlet in a jsp page?
Thanks in advance!
edit:
what I can do is print out the data from the array on the JSP page (in the header) with this code:
<c:forEach items="${graphData}" var="temp">
<c:out value="${temp}"/><br />
</c:forEach>
But I want to use the data from the array in my JS code. which for some reason doesn't work.

You can use like this
<script>
var graphData = [
<c:forEach items="${graphData}" var="graph">
'<c:out value="${graph}" />',
</c:forEach>
];
console.log(graphData);
</script>

Related

JavaScript script won't load contents of a JSON file to process

I am trying to load a JSON file into a JavaScript script for use in a Mustache script on a webpage. The JSON in a string loads correctly, but the same JSON in a file does not.
This works:
function renderHello() {
var json = JSON.parse('{"cloudy": "This applies to Snowflake.","classic": "This applies to SQL Server."}');
var template = document.getElementById("template").innerHTML;
var rendered = Mustache.render(template, json);
document.getElementById("target").innerHTML = rendered;
}
This does not work:
function renderHello() {
var json = JSON.parse('./abc.json');
var template = document.getElementById("template").innerHTML;
var rendered = Mustache.render(template, json);
document.getElementById("target").innerHTML = rendered;
}
Variations I've tried in abc.json:
{
"cloudy": "This applies to Snowflake.",
"classic": "This applies to SQL Server."
}
{"cloudy": "This applies to Snowflake.","classic": "This applies to SQL Server."}
I've unsuccessfully tried
var json = './abc.json';
var json = JSON.parse('./abc.json');
var json = JSON.stringify('./abc.json');
var json = JSON.parse(JSON.parse('./abc.json'));
var json = JSON.parse(JSON.stringify('./abc.json'));
Frequently an error like this is returned in the Chrome Developer Tools:
VM223:1 Uncaught SyntaxError: Unexpected token . in JSON at position 0
at JSON.parse (<anonymous>)
at renderHello (render.js:2)
at onload (docs.html:91)
I added these lines in the script to reveal the location of the website file that includes the Mustache template, so I knew where to locate abc.json:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(dir)
And the file structure is now this:
directory
--file-with-mustache-script.html
--abc.json
This may not be relevant, but this is the Mustache script, which of course already works with the JSON as a string.
<body onload="renderHello()">
<div id="target">Loading...</div>
<script id="template" type="x-tmpl-mustache">
Hello {{ cloudy }}, {{ classic }}!
</script>
</body>
The website build tool I'm using does not support Node or Handlebars.
If it is relevant at all, the goal is to populate values from a JSON file in a product documentation website page to indicate which paragraphs apply to which product version.
You need to load the content of the file via "AJAX". You can't get the content like you are trying to do.
Something like this would do the job:
function renderHello() {
fetch('https://jsonplaceholder.typicode.com/users/3').then(r=>r.json())
.then(json=>{
// var template = document.getElementById("template").innerHTML;
// var rendered = Mustache.render(template, json);
document.getElementById("target").innerHTML = JSON.stringify(json,null,2);
})
}
renderHello();
<pre id="target"></pre>
As I don't have access to your abc.json file I used a publicly resource at http://typicode.com.

Getting text/attributes from a script object function in html using Python

I've been doing web scraping on a website where I need to get the javascript so I could extract data such as name, created date, and some randomly generated codes as will be shown below...
Is there an efficient/any way of getting text/attributes from a script object function in a <script type="text/javascript"> from a html webpage.
I was able to find the script section using BeautifulSoup, with the function embedded in it is as follows:
<script type="text/javascript">
//COMMENT// Some data already here
$(document).ready(function() {
name.init("<website Link>")
lang.init("en", "GB")
data.init("hello", "", "AT3K21SDV", "YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5", "")
});
</script>
Specifically, I need to get the $(document).ready(function() section that will include AT3K21SDV and YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5.
I've been bugging my brains out trying to get it using index like so; `soup[3:40] but doesn't work
beautifulsoup doesn't parse JavaScript, so you need to use other tools. For example re to extract the information:
import re
from ast import literal_eval
txt = '''<script type="text/javascript">
//COMMENT// Some data already here
$(document).ready(function() {
name.init("<website Link>")
lang.init("en", "GB")
data.init("hello", "", "AT3K21SDV", "YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5", "")
});
</script>'''
data = re.search(r'data\.init(\(.*?\))', txt).group(1)
data = literal_eval(data)
print(data[2], data[3])
Prints:
AT3K21SDV YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5
EDIT: If inside data.init(...) are newlines, you must set flags=re.DOTALL in re.search():
import re
from ast import literal_eval
txt = '''<script type="text/javascript">
//COMMENT// Some data already here
$(document).ready(function() {
ab.info.init("sv", "pp", "f", "NONE",
"rw", "3r7u6565667",
"3435345")
});
</script>'''
data = re.search(r'info\.init(\(.*?\))', txt, flags=re.DOTALL).group(1)
data = literal_eval(data)
print(data)
Prints:
('sv', 'pp', 'f', 'NONE', 'rw', '3r7u6565667', '3435345')

can't select specific elements from data contained in <?!=JSON.stringify(dataFromServerTemplate) ?>

I have a problem with JSON format. I'm new at this kind of stuff so I can't figure out which is the problem. In google app script I have this get function
function doGet() {
var htmlTemplate = HtmlService.createTemplateFromFile('html');
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1_cj_HO2oN6CYe_Pb7Cy8S3yVtwKW8Efr-Sdyf1Sk8Ts/edit#gid=2009573145");
htmlTemplate.dataFromServerTemplate = makeJSON(getRowsData_(ss.getSheetByName("Foglio8"),getExportOptions()),getExportOptions());
var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('sample');
return htmlOutput;
}
Now, here is the part of the HTML which isn't working
<div>
<p id="tx"></p>
</div>
<script type="text/javascript">
var data = <?!=JSON.stringify(dataFromServerTemplate) ?>;
function caric(){
document.getElementById("tx").innerText= data.saldo;}
</script>
</body>
Function caric() runs onload of the page. "saldo" is actually contained in this JSON.
If I use data.saldoI receives undefined but if I only use data it works and prints everything that is contained in the JSON.
Do you know what I'm doing wrong?
Thanks
JSON.stringify produces a string not an object. In your server code you should do something like this.
var obj = { name: "me", gender: "male", eyes: "blue" };
htmlTemplate.dataFromServerTemplate = JSON.stringify(obj);
And on the client side this
var data = JSON.parse(<?= dataFromServerTemplate ?>);
(function caric(){
document.getElementById("tx").innerText= data.name;}());

Appending JSTL ArrayList<String> to a Javascript String

I am trying to append a ArrayList to a JavaScript String variable using foreach loop but for some reason it doesn't seem to work. I have been trying to fix this problem for 2 days, but no luck yet. Can anyone help with this? Here's the code.
<div id="graphdiv"></div>
<script type="text/javascript">
var s = "";
<c:forEach items="${dateAndWaitTimes}" var="item">
s.append(${item});
</c:forEach>
g = new Dygraph(document.getElementById("graphdiv"), s);
</script>
Here dateAndWaitTimes contains the ArrayList of String, returned by the controller.
-
Output that I am getting:
Expected Output:
It seems you're getting array values correctly but nothing display correct.
one solution might be : put Java arraylist values into JS arrayList and then print JS arrayList values.
Code :
<script language="javascript">
$(function(){
var values = new Array();
<c:forEach var="item" items="${dateAndWaitTimes}" varStatus="status">
values.push("${item}");
</c:forEach>
alert(" VALUES => "+values[0]);
alert(" VALUES => "+values[1]);
//alert(" VALUES => "+values[2]);
});

JavaScript - How do I open a new page and pass JSON data to it?

I have a page called search.jsp. When the user selects a record and the presses an edit button, I would like to open a new page (in the same window) with the record data (that is stored in a json object and passed to the new page). How do I use Javascript (or jQuery) to open a new page and pass the JSON data?
If the two pages are on the same domain, a third way is to use HTML5 localStorage: http://diveintohtml5.info/storage.html
In fact localStorage is precisely intended for what you want. Dealing with GET params or window/document JS references is not very portable (even if, I know, all browsers do not support localStorage).
Here's some very simple pure JavaScript (no HTML, no jQuery) that converts an object to JSON and submits it to another page:
/*
submit JSON as 'post' to a new page
Parameters:
path (URL) path to the new page
data (obj) object to be converted to JSON and passed
postName (str) name of the POST parameter to send the JSON
*/
function submitJSON( path, data, postName ) {
// convert data to JSON
var dataJSON = JSON.stringify(data);
// create the form
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', path);
// create hidden input containing JSON and add to form
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", postName);
hiddenField.setAttribute("value", dataJSON);
form.appendChild(hiddenField);
// add form to body and submit
document.body.appendChild(form);
form.submit();
}
Use some PHP like this on the target page to get the JSON:
$postVarsJSON = $_POST['myPostName'];
$postVars = json_decode( $postVarsJSON );
Or, more simply for JavaScript:
var postVars = JSON.parse( <?php $_POST['myPostName']; ?> );
Assuming the two pages are on the same domain, you can use the returned object created by window.open() to access (and edit) the window object of a newly opened window.
Hmm, for example, you have object
var dataObject = {
param : 'param',
param2 : 'param2'
};
You can translate it into string, using JSON.stringify method
var dataObjectString = JSON.stringify(dataObject);
Then you should use Base64 encoding to encode you data (base64 encode/decode methods can be easely found in search engines)
var dataObjectBase64 = base64encode(dataObjectString);
You will get something like this
e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307
Then you can pass this string as a parameter:
iframe src="http://page.com/?data=e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307"
Finally, reverse actions on the loaded page.
You can create "on the fly" a form with a hidden/text input value this will hold the json value, then you can submit this form via javascript.
Something like this...
Im using JQUERY AND UNDERSCORE(for template purpose)
this is the template
<form method='<%= method %>' action="<%= action %>" name="<%= name %>" id="<%= id %>" target="_blank">
<input type='hidden' name='json' id='<%= valueId %>' />
</form>
you can then post use it on javascript
function makePost(){
var _t = _.template("use the template here");
var o = {
method : "POST",
action :"someurl.php",
name : "_virtual_form",
id : "_virtual_form_id",
valueId : "_virtual_value"
}
var form = _t(o); //cast the object on the template
//you can append the form into a element or do it in memory
$(".warp").append(form);
//stringify you json
$("#_virtual_value").val(JSON.stringify(json));
$("#_virtual_form_id").submit();
$("#_virtual_form_id").remove();
}
now you dont have to be worry about the lenght of you json or how many variables to send.
best!
If the the JSON is small enough you can just include it as a GET parameter to the URL when you open the new window.
Something like:
window.open(yourUrl + '?json=' + serializedJson)
Assume if your json data
var data={"name":"abc"};
The page which sends JSON data should have the following code in the script tag.
$.getJSON( "myData.json", function( obj ) {
console.log(obj);
for(var j=0;j
<obj.length;j++){
tData[j]=obj;
//Passing JSON data in URL
tData[j]=JSON.stringify(tData[j]);
strTData[j]=encodeURIComponent(tData[j]);
//End of Passing JSON data in URL
tr = $('\
<tr/>
');
//Send the json data as url parameter
tr.append("
<td>" + "
" +Click here+ "" + "
</td>
");
}
});
The page which receives the JSON data should have the code.
<html>
<head></head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<body>
<p id="id"></p>
</body>
<script type="text/javascript">
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.jsonDATA);
var name=data.name;
console.log(name);
document.getElementById("id").innerHTML=name;
} catch (err) {
alert(err + "\nJSON=" + q.team);
}
</script>
</html>

Categories