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 !
Related
Goal :
1. Extract csrf value from my GET request response body
2. Store extracted 'csrf' value in environment variable
3. Use it in subsequent POST request.
Found a Solution and working:
var matchSETTINGS cheerio.load(responseBody);
Extract var matchSETTINGS = text.match(var a= (.*););
This is bit complicated, but achievable using various ways. Here I'm showing you a static way, change it as per your requirement.
Postman supports cheerio library, that you can use to parse HTML responses.
var html = cheerio(responseBody);
//get script tag data
var htmlData = html[14].children[1].children[5].children[0].data;
var csrfIndex = htmlData.search(/'csrf'/i);
var dataBeforeCsrf = htmlData.slice(0, csrfIndex);
//remove content before csrf node
htmlData = htmlData.replace(dataBeforeCsrf, '');
//to make it in right format of JSON, replace single quote with double,
//remove ; and add bracket
htmlData = htmlData.replace(/'/g, '"');
htmlData = htmlData.replace(';', '');
//parse to JSON
var jsonData = JSON.parse('{' + htmlData);
//print csrf
console.log(jsonData.csrf);
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]);
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
$( document ).ready(function() {
console.log( "ready!" );
var ilceler = "${ilceler}";
});
It doesn't print "Ready!" to console. When I debug with chrome, I saw
$( document ).ready(function() {
console.log( "ready!" );
var subChildList = "";
ilceler = JSON.parse(" [
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"},
{"id":"x","tag":"xx","name":"xxx xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xx\/xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxx","fatherid":"66","fathertag":"il"},
{"id":"xx","tag":"xx","name":"xxxx","fatherid":"66","fathertag":"il"}]");
});
My data is true, but why this function doesn't work.
Note: My data includes UTF-8 characters.
Note2: I can work with string instead of json.
var a = ${tag}
console.log(a) >> "It's my tag"
I seems to me that you need to remove the quotes surrounding your variable.
So it should be
var ilceler = ${ilceler};
The JSP/JSTL interpreter will leave these quotes and hence your object will be regarded as a String value instead of a JSON object. Also if your second output is the output in the browser you can see it's not valid JSON.
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.