views:

498

answers:

2

I'd like to load a JSON feed from an external source using Javascript; what's the best method? I've been working a lot in PHP where it would be easy to do so with file_get_contents or cURL. Is there a related function or process in Javascript?

+3  A: 

Javascript XMLHTTPRequest has same-domain origin policy so you will be restricted to only loading data from URLs from the same domain that your script was loaded from. JSONP is one way to get around this. Another way is to use a proxy script on your domain, which in turns performs its own HTTP calls for you. For more information on JSONP check out this article:

http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

Cody Caughlan
+3  A: 

jQuery to get some JSON data might look like this:

$.getJSON("http://pathtodata.js", function(json){
  alert(json.dot.notation);
});

A source is specified along with a callback function. Read up on jQuery JSON documentation: docs.jquery.com/Ajax/jQuery.getJSON

tb
That's exactly it. jQuery both imports and parses which, if you're already using the library, makes things really quite simple. Just make sure you load it in the <head> :)
Daniel Bachhuber