Parse XML returned data from foreign domain request - javascript

I'm trying to parse XML data returned from a foreign website. I use a domain request to send some variables to a website like this : http://www.url.com/page.php?var1=val1&var2=val2...
I get this back appended inside a <div> :
<!--?xml version="1.0" encoding="UTF-8"?-->
<liste>
<produits>
<produit>
<nomprod>Title</nomprod>
<desc>Desc</desc>
<texte>Text</texte>
<url>http://www.url.com</url>
</produit>
</produits>
</liste>
I would like to parse these datas and show them in my page correctly
Any help would be very appreciated, Thanks!

JKL.ParseXML is a really simple to use library you might want to look at. You can get values from your xml with this super simple code
var xml = yourXMlInAString,
data = xml.parse(),
title, desc, text, url;
title = data["liste"]["produits"]["produit"]["nomprod"];
desc = data["liste"]["produits"]["produit"]["desc"];
text = data["liste"]["produits"]["produit"]["text"];
url = data["liste"]["produits"]["produit"]["url"];
Then you can do what you want with the data, that's of course up to you.
Alternatively, jQuery also makes parsing XML, thought I would understand if you opted for the lighter library! If you were to use it, you'd want to look at the parseXML function, there's good documentation on the function's page, so take a look there if you opt for jQuery.

Related

Correct parsing of JSON

First of all, forgive me if any of this code is bad, inefficient, or completely wrong, I haven't worked with JSON at all before, or any sort of API work.
So, I'm just trying to create a basic webpage which will display some information from the JSON obtained through JSONP (did I implement it correctly...?). I thought that I was accessing the id element correctly but it seems not as I've tried getting it to show up with alert, console.log, and setting the inner html of the paragraph. Here is the code:
HTML
</head>
<body>
<p id="main">
test
</p>
</body>
<script src="js/parseJSON.js"></script>
<script type="application/json" src="https://www.aviationweather.gov/gis/scripts/MetarJSON.php?taf=true&bbox=-86,41,-82,45&callback=parseJSON"></script>
</html>
Javascript
var parseJSON = function(json) {
var obj = JSON.parse(json);
console.log(obj.features[0].properties.id);
}
This seems like something simple I'm just screwing up. Any help would be appreciated, thanks!
I'm just trying to create a basic webpage which will display some information from the JSON obtained through JSONP (did I implement it correctly...?).
You said type="application/json" so the browser ignored it because it doesn't know how to execute scripts written in JSON.
JSONP is not JSON, it is JavaScript, so the correct Content Type is application/javascript.
Further https://www.aviationweather.gov/gis/scripts/MetarJSON.php?taf=true&bbox=-86,41,-82,45&callback=parseJSON returns JSON not JSONP.
var parseJSON = function(json) {
var obj = JSON.parse(json);
While it is possible for a JSONP service to provide data in the form of a JavaScript string containing JSON, that is never something I've seen. The argument should not be parsed as JSON. It should be a regular JavaScript data structure.
… but first you need the service to return JSONP.

node.js does not recognise the url in the unfluff module

Any help will be appreciated.
I need to extract data from websites and found that node-unfluff does the job (see https://github.com/ageitgey/node-unfluff). There is two ways to call this module.
First, from command line which works!
Second, from node js which doesn't work.
extractor = require('unfluff');
data = extractor('test.html');
console.log(data);
Output : {"title":"","lang":null,"tags":[],"image":null,"videos":[],"text":""}
The data returns an empty json object. It appears like it cannot read the test.html.
It seems like it doesn't recognise test.html. The example says, "my html data", is there a way to get html data ? Thanks.
From the docs of unfluff:
extractor(html, language)
html: The html you want to parse
language (optional): The document's two-letter language code. This
will be auto-detected as best as possible, but there might be cases
where you want to override it.
You are passing a filename, and it expects the actual HTML of the file to be passed in.
If you are doing this in a scripting context, I'd recommend doing
data = extractor(fs.readFileSync('test.html'));
however if you are doing this in the context of a server or some time when blocking will be an issue, you should do:
fs.readFile('test.html', function(err, html){
var data = extractor(html);
console.log(data);
));

Servlet calling from window.showModalDialog(...)

I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks

Using jQuery on a string containing HTML

I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)

JQuery and JSON

Here's something I want to learn and do. I have a JSON file that contains my product and details (size, color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.
First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)
How to parse the JSON datas that were searched into an HTML?
How to add details, product to the JSON file?
It will also be great if you can point me to a good tutorial about my questions.
I'm new to both JQuery and JSON.
Thanks!
Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.
Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.
Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:
$.getJSON("getProductJSON.htm",
function(data) {
$.each(data.products, function(i, item) {
var name = item.name;
var price = item.price;
// now display the name and price on the page here!
});
},
);
Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.

Categories