I'm facing a problem which should be really simple to solve, but I am lost as of now.
I have a url: http://search.twitter.com/search.json?q=bacon
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
Thanks!
You'll be restricted by the SOP (XMLHttpRequests can only be made to URI's on the same domain; JSON can only be retrieved via this method). To bypass this you'll have to use JSONP instead (other explanation*).
It seems the endpoint supports JSONP, so you can do:
function foo(response) {
// response is already a JavaScript object
}
var script = document.createElement("script");
script.src = "http://search.twitter.com/search.json?q=bacon&callback=foo";
document.body.appendChild(script);
* Disclaimer: Yep, thats my blog
Related
I have been trying to get basic JSONP working in Dart and I am getting stuck. Reading this blog post as well as this this blog show that I should use window.on.message.add(dataReceived); to get a MessageEvent and retrieve data from the event.
Dart complains that "There is no such getter 'message' in events". In addition, I looked up different ways of getting a MessageEvent but it seems to be something completely unrelated (WebSockets?) and is not what I actually need.
If anybody can explain what is going on and how to really use JSONP in Dart, that would be awesome!
You don't need to use what is described in the articles you point anymore. You can use dart:js :
import 'dart:html';
import 'dart:js';
void main() {
// Create a jsFunction to handle the response.
context['processData'] = (JsObject jsonDatas) {
// call with JSON datas
};
// make the call
ScriptElement script = new Element.tag("script");
script.src = "https://${url}?callback=processData";
document.body.children.add(script);
}
I recently wrote a blog post on this myself as I was running into similar problems.
I first cover a few prerequisite things like Verifying CORS Compliance and Verifying JSONP Support
I too ended up registering with the updated method:
window.onMessage.listen(dataReceived);
I then had a fairly simple method to dynamically create the script tag in Dart as well (my requirement was that I had to use Dart exclusively and couldn't touch the website source files):
void _createScriptTag()
{
String requestString = """function callbackForJsonpApi(s) {
s.target="dartJsonHandler";
window.postMessage(JSON.stringify(s), '*');
}""";
ScriptElement script = new ScriptElement();
script.innerHtml = requestString;
document.body.children.add(script);
}
I then invoked it from Dart with some simple logic that I wrapped in a method for convenience.
void getStockQuote(String tickerId)
{
String requestString = "http://finance.yahoo.com/webservice/v1/symbols/" + tickerId + "/quote?format=json&callback=callbackForJsonpApi";
ScriptElement script = new ScriptElement();
script.src = requestString;
document.body.children.add(script);
}
If you are using dart:js I find Alexandre's Answer useful and, after upvoting Alexandre, I have updated my post to include the simplified version as well:
context['callbackForJsonpApi'] = (JsObject jsonData)
{
//Process JSON data here...
};
This obviously eliminates the need for the onMessage and _createScriptTag above, and can be invoked the same as before.
I decided to keep both approaches, however, as I have noticed over time the Dart APIs changing and it seems to be a good idea to have a fallback if needed.
The syntax has changed
window.onMessage.listen(dataReceived);
This code is on a Button onClick event:
function loadJSONData(url) {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
headID.appendChild(newScript);
}
loadJSONData('http://api.lemonfree.com/listings?key=2806cdf10605dc9598b1cf3a2387acb7&make=HUMMER&model=H2&zip=80901&distance=100&per_page=25&sortby=Price&sortdir=ASC&year_from=2005&year_to=2008&format=json&callback=processJSONData');
This code is in the Load JavaScript area
function processJSONData(data){
alert( "Id: " + data.response.requestType );
console.log( 'Id:' );
console.log( data.response.requestType );
}
When I press the Button the onclick event fires and the below JSON data is returned.
The problem is that I cannot figure out how to reference the data with it.
I have tried everthing that I can think of to access the data elements.
data.response.requestType,
data.response.result[0].id
response.requestType,
response.result[0].id
etc.
www.jsonlint.com validates the returned data as valid json also
jsonviewer.stack.hu also validates the returned data as valid json.
Any HELP would be greatly appreciated.
Mark
If you enter this into your browser you will receive the data that is returned
http://api.lemonfree.com/listings?key=2806cdf10605dc9598b1cf3a2387acb7&make=HUMMER&model=H2&zip=80901&distance=100&per_page=25&sortby=Price&sortdir=ASC&year_from=2005&year_to=2008&format=json&callback=processJSONData
Your loadJSONData function actually uses JSONP, so you don't need to parse anything at all - data would just be the object.
Only the lemonfree api does not seem to support JSONP, the ressource you linked to is plain JSON - the callback "padding" is missing. And the SOP prevents you from accessing it directly via Ajax, so you'll need to use some kind of proxy.
I have a page which redirects to a url from parameters in query string like:
page.html?redirectUrl=index.html
Inside the page i have code like this:
window.localtion.href = redirectUrl;
It is requiements to use redirect url by parameters. The page contains secure sensitive data. Someone can make the url with javascript like:
page.html?redirectUrl=javascript:alert(document.getElementById("password").value)
and secure data can be stolen.
How to prevent bypass javascript code to window.localtion.href?
You might try putting the URL in an anchor element and checking the protocol:
var anchor = document.createElement("a");
anchor.href = redirectUrl;
if(anchor.protocol != "javascript:") {
window.localtion.href = redirectUrl;
}
However, I'm not sure how good the browser support is for this, since MDN lists it as an HTML5 feature.
This seems like it would work as long as you're not redirecting with it:
Javascript:
var field = document.getElementById("redirectUrl");
var newValue = String(field.value);
alert(newValue);
Basically, using the String constructor to "sanitize" the input.
These will probably help more with other cases:
https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
Overall, I would recommend NOT using Javascript to sanitize input. If you're handling really sensitive or important data you are highly recommended to use a server-side language to validate and sanitize your input.
I thought this question would be trivial but I just can't seem to find an answer.
A website (different origin, no control over it) is making available some JSON files. I want some variables of my script to grab the content of those files. I don't care whether it is done synchrnously or not. How would you go ?
using JSONP consist of using your url, with parameters, and add a script file to your page
www.example.com/process?value=1&callback=Func
add the script to your page.
var url = "www.example.com/process?value=1&callback=Func";
var script = document.createElement('script');
script.type= ' text/javascript';
script.src = url;
document.getElementsByTagName("body")[0].appendChild(script);
now you can use the call back function or access the variables that were added from this script.
UPDATE
At the end of your jsonp script you can call your call back function
Ex: php
<?php
if (isset($_GET['callback'])) {
echo $_GET['callback']."();";
// Func(); // will call your function and use your variables.
}
If the remote host does not supply JSONP or CORS, then you will need to place a server-side component on your own domain which fetches the JSON for you and serves it locally.
Hi i want to parse xml/rss from a live url like http://rss.news.yahoo.com/rss/entertainment using pure Java Script(not jquery). I have googled a lot. Nothing worked for me. can any one help with a working piece of code.
(You cannot have googled a lot.) Once you have worked around the Same Origin Policy, and if the resource is served with an XML MIME type (which it is in this case, text/xml), you can do the following:
var x = new XMLHttpRequest();
x.open("GET", "http://feed.example/", true);
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
// …
}
};
x.send(null);
(See also AJAX, and the XMLHttpRequest Level 2 specification [Working Draft] for other event-handler properties.)
In essence: No parsing necessary. If you then want to access the XML data, use the standard DOM Level 2+ Core or DOM Level 3 XPath methods, e.g.
/* DOM Level 2 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].firstChild.nodeValue;
/* DOM Level 3 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].textContent;
/* DOM Level 3 XPath (not using namespaces) */
var title = doc.evaluate('//channel/title/text()', doc, null, 0, null).iterateNext();
/* DOM Level 3 XPath (using namespaces) */
var namespaceResolver = (function () {
var prefixMap = {
media: "http://search.yahoo.com/mrss/",
ynews: "http://news.yahoo.com/rss/"
};
return function (prefix) {
return prefixMap[prefix] || null;
};
}());
var url = doc.evaluate('//media:content/#url', doc, namespaceResolver, 0, null).iterateNext();
(See also JSX:xpath.js for a convenient, namespace-aware DOM 3 XPath wrapper that does not use jQuery.)
However, if for some (wrong) reason the MIME type is not an XML MIME type, or if it is not recognized by the DOM implementation as such, you can use one of the parsers built into recent browsers to parse the responseText property value. See pradeek's answer for a solution that works in IE/MSXML. The following should work everywhere else:
var parser = new DOMParser();
var doc = parser.parseFromString(x.responseText, "text/xml");
Proceed as described above.
Use feature tests at runtime to determine the correct code branch for a given implementation. The simplest way is:
if (typeof DOMParser != "undefined")
{
var parser = new DOMParser();
// …
}
else if (typeof ActiveXObject != "undefined")
{
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
// …
}
See also DOMParser and HTML5: DOM Parsing and Serialization (Working Draft).
One big problem you might run into is that generally, you cannot get data cross domain. This is big issue with most rss feeds.
The common way to deal with loading data in javascript cross domain is calls JSONP. Basically, this means that the data you are retrieving is wrapped in a javascript callback function. You load the url with a script tag, and you define the function in your code. So when the script loads, it executes the function and passes the data to it as an argument.
The problem with most xml/rss feeds is that services that only provide xml tend not to provide JSONP wrapping capability.
Before you go any farther, check to see if your data source provides a json format and JSONP functionality. That will make this a lot easier.
Now, if your data source doesn't provide json and jsonp functionality, you have to get creative.
On relatively easy way to handle this is to use a proxy server. Your proxy runs somewhere under your control, and acts as a middleman to get your data. The server loads your xml, and then your javascript does the requests to it instead. If the proxy server runs on the same domain name then you can just use standard xhr(ajax) requests and you don't have to worry about cross-domain stuff.
Alternatively, your proxy server can wrap the data in a jsonp callback and you can use the method mentioned above.
If you are using jQuery, then xhr and jsonp requests are built-in methods and so make doing the coding very easy. Other common js libraries should also support these. If you are coding all of this from scratch, its a little more work but not terribly difficult.
Now, once you get your data hopefully its just json. Then there's no parsing needed.
However, if you end up having to stick with an xml/rss version, and if you're jQuery, you can simply use jQuery.parseXML http://api.jquery.com/jQuery.parseXML/.
better convert xml to json. http://jsontoxml.utilities-online.info/
after converting if you need to print json object check this tutorial
http://www.w3schools.com/json/json_eval.asp