Hi I am trying to fetch portlet session in my JS variable. How could I go about it
request.getPortletSession().getAttribute("countryList"); //This is my .java class code
I need to fetch the same in JS?
you can't access to java session via javascript.
One solution is to serialize you java object into json string and save it into session(if object is null, just save a string that equals to "null")
getPortletSession().setAttribute("countryListJson", JSONUtil.toJSON(yourObject));
then you can use
<script type="text/javascript">
var obj = <%=request.getPortletSession().getAttribute("countryListJson")%>;
</script>
Another solution is to provide a json padding controller method for ajax call. and return a string like this :
return "var countryList = " + JsonUtil.toJson(request.getPortletSession().getAttribute("countryList")) +";"
then you should mapping this method to a url such as "/contryList.do"
and in your page:
<script type="text/javascript" src="<%=request.getContextPath()%>/contryList.do"></script>
<script type="text/javascript">
alert(contryList);
</script>
As i understand, you need to place in some JS var the countryList (from controller). You don't need to get portlet session in JS, you should be able to do like follows:
I managed to get some strings from controller to js using scriptlets and usebean. Try something like this:
Let's say i need to alert an error from backend and i have put it in a java string named "error"(in controller).
I'm able to do this(doView):
String error = request.getAttribute("error"); // or it can be simply String error = "sometext"
if ((error != null) || (!error.equals(""))){
request.setAttribute("error", error);
}
else request.setAttribute("error","false");
Then, in your jsp, at the top i'll place an usebean tag like:
<jsp:useBean id="error" class="java.lang.String" scope="request"></jsp:useBean>
Then, between script tags:
var error = "<%=error%>";
if (error != "false") alert(error);
As i noticed, you need to set the var in controller (with setAttribute) using an if / else statement.
Related
I want to include javascript list string in template at quarkus app.
I define ConfigProperty like this.
#ConfigProperty(name = "my_list_string")
lateinit var myListStrings: List<String>
And I use this at template like this.
<script type="text/javascript">
var myListString = {myListStrings};
myJSFunc(myListString);
</script>
When I set my_list_string=test, output is below.
<script type="text/javascript">
var myListString = [test];
myJSFunc(myListString);
</script>
The myJSFunc needs list string, so I want to get ['test']
Also, I set my_list_string="'test'", the output is below.
<script type="text/javascript">
var myListString = ['test'];
myJSFunc(myListString);
</script>
If anyone know how to set JavaScript list string at quarkus app, please tell me about it.
Thank you.
Environment
Java 11
Quarkus 1.5.2
The #ConfigProperty happens on the server side (in Java).
You'll need to expose a REST method to get it the value of that property on the client side (in JavaScript).
Something like
#ConfigProperty(name = "my_list_string")
lateinit var myListStrings: List<String>
#Path("/my_list_string")
String getMyListString() {
return my_list_string;
}
And then retrieve that in your .js file, probably in the document is loaded event.
I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.
#RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
public String getRcaResult(Model model, String flight_id) {
...
JSONObject all = new JSONObject ();
...
model.addAttribute("all",all);
return "dfi/rca";
}
I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:
<script type="text/javascript">
var all= "${all}";
</script>
But if I try the same importing a Javascript file in the JSP, it doesn't get anything:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>
In all.js:
var rcaresults = JSON.parse('${all}');
Are there any way to read the Spring model attributes in a Javascript file?
Thanks in advance.
JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.
If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.
e.g <script>var paramOne =<c:out value="${all}"/></script>
when you use src, your browser (and not your backend) will try to fetch the javascript file from
"${pageContext.request.contextPath}/resources/js/all.js"
so the file is not processed by the server as a ModelView.
I know how to pass data with a jinja template from python into javascript, but I want to pass a javascript variable into python. I'd like to do it without reloading the page. Is that possible?
Yes, like monkut said--I believe you want to use JSON and Javascript/jQuery.
This will let allow communication from client to server and back again.
The most applicable example I found was in the Flask snippets/patterns: http://flask.pocoo.org/docs/patterns/jquery/
I did a similar kind of work in my project and would like to share my code here. I need to find out which post is selected and I was setting the selected post as a global variable at server side, so that I may use it for later comparison. This is how I pass my selected post into Javascript.
<a class="label label-primary" onclick="myFunction({{very.id}})" > Compare</a>
Now from Javascript to Flask.
function myFunction(x) {
$.getJSON($SCRIPT_ROOT + '/check_selected', {
post: x
}, function(data) {
var response = data.result;
console.log(response);
}
});
}
This is how I return the result from flask by using JSON.
import json
#main.route('/check_selected', methods=['GET','POST'])
def check_selected():
global selected
post = request.args.get('post', 0, type=int)
return json.dumps({'selected post': str(post)});
As mentioned here, we need to include Google AJAX API in order to load jquery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{
url_for('static', filename='jquery.js') }}">\x3C/script>')</script>
Create a JSON string from your view code say, jsonData and in your Jinja Template, write something like
<script type="text/javascript">
var data = {{ jsonData }};
</script>
Can I assign a javascript variable to a grails object like this?
var newReport = ${report};
report is a grails domain object, which is passed back from controller to the gsp file.
Currently this doesn't work in my page.
Assuming that report is a Grails domain class, you will have to 'translate' this to a valid javascript format. One way is to set this as JSON. Something like:
In the controller
def reportJson = report as JSON
In the gsp
<script type='text/javascript'>
var newReport = $.parseJSON("${reportJson}");
</script>
The parseJSON takes the json string and return a javascript object.
Just render domain object as JSON to gsp, where some javascript code get the json by eval() function. For instance:
domain class - Band:
String bandName //some property
...
controller:
def bands = Band.list()
render(template:"result", model:[bands:bands as JSON]
_result.gsp:
<script>
var bandList = eval(${bands});
for(i=0; i<bandList.length; i++){
var name = bandList[i].bandName;
....
}
....
</script>
I need to generate a JSON object from server containing data to be cached on client. I placed the following:
<script src='Path to js file on server" />
At the server, I generated my json data and placed them inside the JS file.
I can see the generated JSON object on the client-side something as:
var jsonData = [{}, {}];
However, when I try to access jsonData object, it says, undefined!
Is there another way to generate valid javascript from server side?
Thanks
This is the server-side code:
var items = List<myObj>();
string json = JsonConvert.SerializeObject(items, Formatting.Indented);
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendFormat(" var jsonData = {0};", json);
var fileName = Request.PhysicalApplicationPath + "Scripts/Data.js";
System.IO.File.WriteAllText(fileName, sb.ToString());
As for client side:
<script src='#Url.Content("~/Scripts/Data.js")' type="text/javascript"></script>
I tried to use this code on the client:
alert(jsonData[0].Id);
It says, jsonData is undefined!
Regards
ASP part is ok, the problem seemed to lie in javascript variable scoping plane. Possible problems:
You just don't include that js file.
You're trying to access variable before it is initialized;
Variable isn't visible in place, you're trying to access it.
You're not exact in your question and accessing not jsonData, but something like jsonData[0].property
etc.
UPD: Ok, first two options are excluded. Where are you trying to access this variable? Please, show us a portion of code.