Im trying to pass a Collection of items converted into String with JsonArray to my Javascript but dont work.
This is the code of the class
InformeAmenazasAGR = manager.preparaInformeRiesgoActivos(idDimension, tipoActivo, idActivo, tipoActivoTexto, nombreActivo, recursos);
JSONArray JSonArray = new JSONArray();
JSonArray.put(InformeAmenazasAGR);
String texto = JSonArray.toString();
//Delete the first and last char.
texto = texto.substring(1, texto.length()-1);
request.setAttribute("InformeAmenazasAGR", texto);
return mapping.findForward( "informeActivosAGR" );
This returns one String like this:
[
["16","E.1","Errores de los usuarios","7","1128750","1015875"],
["20","E.5","Deficiencias en la organizaciĆ³n","7","752500","526750"],
]
My JSP with Javascript (im using ExtJS and follow I tried Passing a Java string to Javascript post but dont work)
var DatosAmenazas = new String("<%request.getAttribute("InformeAmenazasAGR");%>");
var amenazaStore = Ext.create('Ext.data.Store', {
model: 'Amenazas',
data: DatosAmenazas
});
What am i doing wrong?
Thank you in advance
EDIT: If i put the raw String that i save in request.setAttribute("InformeAmenazasAGR", texto); it works:
var amenazaStore = Ext.create('Ext.data.Store', {
model: 'Amenazas',
data: [
["16","E.1","Errores de los usuarios","7","1128750","1015875"],
["20","E.5","Deficiencias en la organizaciĆ³n","7","752500","526750"],
]
});
I think using the Java scriptlet inside javascript is not good practice,
instead you can use the $(InformeAmenazasAGR) to set the request attribute value to a hidden element and put the hidden element anywhere inside your html <body> like this,
<input type="hidden" id="jsonData" value="${InformeAmenazasAGR}">
then, get the hidden element value like,
var DatosAmenazas = new String($('#jsonData').val());
if you need the request attribute InformeAmenazasAGR to be converted into json data then instead of above you can change your above line as,
var DatosAmenazas = JSON.parse($('#jsonData').val());
FYI: Java scriptlets run on server side while javascript on client side
Related
I have this JSON data
"posts":[{
"date":"2016-02-10 10:28:42",
"categories":[{}],
"tags":[],
"author":{"name":"admin"},
"custom_fields":{
"ref_number":["ITB NUMBER: ITB\/002\/2016"],
"deadline":["26 February, 2016"],
"entity":["Refugees (xxx)"]
}
I want to pass entitywith the code below in my JSONParser.java
Post post = new Post();
// Configure the Post object
post.setTitle(postObject.optString("title"));
post.setDate(postObject.optString("date", "N/A"));
post.setContent(postObject.optString("content", "N/A"));
post.setCfs(postObject.getJSONObject("custom_fields").optJSONArray("entity").getString(0));
to my Webview. using the code below in my PostFragment.java
id = args.getInt("id");
//Title and date pass successfully
title = args.getString("title");
String date = args.getString("date");
//but the entity displays null
entity = args.getString("entity");
//author is passed and it displays well/successfully
String author = args.getString("author");
// Construct HTML content
// html for entity to webview
html += "<h2>" + entity + "</h2>";
html += "<h3>" + title + "</h3>";
// The actual content
html += content;
am able to pass and display title and content, however when i try entity it shows null in webview
Where am i going wrong
Try:
entity = args.getString("custom_fields.entity");
Hope it helps!
Your question is not clear , as per my understanding you need Refugee element
The JSON you have posted is not valid.
As per my understanding elements of entity is also an JSONObject , so the parser should be like this
.optJSONArray("entity").getJSONObject(i); // i is poistion
This will give you ith element of entity array
I am parsing the html from the following webpage using Jsoup. How do I get the value from the variable price_ourBase:
<script type="text/javascript">
var price_ourBase = 279;
.
.
.
</script>
JS:
Element upperContainer_inner = document.select("div.upperContainer_inner").first();
Element table = upperContainer_inner.select("table.645.0.left.0.0").first();
Element script = table.select("script").first();
Element base_ourPrice = script.select("base_ourPrice").first();
price = (?, not sure what to put here or if there is more code needed).text();
I dont think jSoup can parse javascript like that. But, you could select the contents of the script with jSoup and then you could do something like
String[] result = script.toString().split(" ");
if(result[1].equals("price_ourBase"))
System.out.println("Our price is "+result[3].split(";")[0]);
I am able to have the response from a servlet and also able to show it on jsp page, but if I try to populate the same in a drop down, i am not able to-
Servlet code
String sql = "SELECT records from department";
ResultSet rs = s.executeQuery(sql);
Map<String, String> options = new LinkedHashMap<String, String>();
while (rs.next()) {
options.put(rs.getString("records"),rs.getString("records"));
}
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
JSP code---
JS code
<script type="text/javascript">
$(document).ready(function () { // When the HTML DOM is ready loading, then execute the following function...
$('.btn-click').click(function () { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('/testservlet', function (responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
//alert(responseJson);
var $select = $('#maindiv'); // Locate HTML DOM element with ID "someselect".
$select.find('option').remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function (key, value) { // Iterate over the JSON object.
$('<option>').val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
});
});
});
</script>
HTML Code--
<input type="button" class="btn-click" id="best" value="check"/>
<div id="maindiv" style="display: block"></div>
If I create a <ul> and <li> I can have the data from the response on my page but not able to create the select options? Any help on this would be great.
Try it again after removing beginning /.
$.get('testservlet', function (responseJson)
The JSON string is not in proper way. It should be something like this. Why are you using JSON string here whereas you are passing only records as key as well as value.
Simply return a comma separated string from Servlet and split it jQuery.
Find example here for Iterating a comma separated string
Sample code:
var items = responseJson.split(',');
for ( var i = 0; i < items.length; i++) {
$('<option>').val(items[i]).text(items[i]).appendTo($select);
}
I want to retrieve a value of a javascript section in a PHP file with my application in Java.
The PHP page contain something like :
<script type="text/javascript">
var tab= new Array();
tab[0] = "value0";
tab[1] = "value1";
tab[2] = "value2";
</script>
I'm using jsoup for parsing the HTML tag. I tried to use Rhino but I don't find example.
Context context = Context.enter();
Scriptable scope = context.initStandardObjects();
Object result = null;
Reader reader = new InputStreamReader(inputStreamOfThePage);
result = context.evaluateReader(scope, reader, "page", 1 , null );
Scriptable varValue = (Scriptable)scope.get("tab", scope);
String valueStr = (String)varValue .get("tab[0]", varValue );
It's giving me the exception :
java.lang.ClassCastException: org.mozilla.javascript.UniqueTag cannot be cast to org.mozilla.javascript.Scriptable
I don't know how to cast the object. Maybe there is a better way to do what I want.
Thanks
Jsoup is not suitable to parse Javascript... It's normal it doesn't work !
I am making a simple html servlet program where I need get JSON object from the servlet, and in html I am able to get the data, but how can i refer to each attribute?
Here is the servlet get method
PrintWriter out=response.getWriter();
StringBuffer emps = new StringBuffer("{employees:[");
emps.append("{fullname:\"Abhishek Raj Simon\"},{email:\"a#a.com\"}]");
emps.append("}");
out.println(emps);
JS to send
function getJson()
{
var url_action="/temp/jsontest";
var form=document.forms["mainForm"];
var splitOutput;
var client;
var dataString;
if (window.XMLHttpRequest){
client=new XMLHttpRequest();
} else {
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function(){
if(client.readyState==4&&client.status==200)
{
var res=client.responseText;
alert(res);
alert(client.responseText.employees.fullname); //DOES NOT WORK
alert(client.responseText.employees.email); //DOES NOT WORK
}
};
client.open("GET",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send();
and a simple form
<form>
<input type="button" value="get me some json" onclick="getJson();">
</form>
When i click on the button, i get only 1 alert displaying {employees:[{fullname:"Abhishek Raj Simon"},{email:"a#a.com"}]} How can i fetch Abhishek Raj Simon and a#a.com using fullname and email respectively?
Edited after reading post from Artem
my servlet
Gson gson = new Gson( );
List<Employee> employees = new ArrayList<Employee>();
Employee emp=new Employee();
emp.setFullname("Abhishek Raj Simon");
emp.setEmail("a#a.com");
employees.add(emp);
response.setContentType( "application/json");
out.println( gson.toJson( employees));
js part
var res=eval('(' + client.responseText + ')');
alert(res);
alert(res.employees.fullname);
alert(res.employees.email);
I think you should slightly change the JSON that you send form the servlet: {employees:[{fullname:"Abhishek Raj Simon", email:"a#a.com"}]} would work a bit better in that context.
I'd recommend jQuery as pap has also advised. The code would be:
$.getJSON('/temp/jsontest', function(data) {
var items = [];
for (employee in data.employees) {
items.push(employee.fullname + '<' + employee.email + '>');
}
alert('Employees: ' + items.join(', '));
});
In my opinion it is lot simpler and easier to understand than dealing with raw XHR. The jQuery $.getJSON will do GET for you, and then evaluate the JSON response so the function is presented with nice JSON representation of your data that is easy to manipulate.
EDIT:
After interesting discussion here is some more improvement you could introduce in order to replace the low-level code with proper JQuery-based implementation.
<script>
$(document).ready(function() {
$("#json-button").click(function() {
$.getJSON('/temp/jsontest', function(data) {
var items = [];
for (employee in data.employees) {
items.push(employee.fullname + '<' + employee.email + '>');
}
alert('Employees: ' + items.join(', '));
});
});
});
</script>
<form>
<input id="json-button" type="button" value="get me some json">
</form>
I would suggest you to use GSON library, which enables you to serialize Java object to json, to avoid writing it by yourself. If you do not want to use GSON, there are plenty of others libraries which uses same capabilities.
//inside your get method
Gson gson = new Gson( );
List<Employe> employees = new ArrayList<Employe>( );
// populate your list here
response.setContentType( "application/json");
response.getWriter( ).println( gson.toJson( employees));
//end
then in javascript you can do as it's already suggested in other answers here. And do pay attention to update response content type.
var res=client.responseText;
var temp = 'resObj=' + res;
eval(temp);
alert(resObj.employees.fullname);
JSON is just text, but in javascript syntax. You need to pass it through the "eval" method that will evaluate and execute the text as javascript.
My advice, though, is to use jQuery or some other javascript framework to avoid having to mess with all that boiler-plate javascript.
It's because you are receiving the JSON String but you're not converting it into a JSON Object. There's a eval() function that evaluates your JSON String and returns a JSON Object.
The following example should work (though untested).
if(client.readyState==4&&client.status==200)
{
var res=eval('(' + client.responseText; + ')');
alert(res);
alert(res.employees[0].fullname);
alert(res.employees[0].email);
}
WARNING: I suggest reading the security concerns when using eval(). Alternatively, go to JSON.org and download a Javascript JSON parser or use JQuery instead.