views:

674

answers:

3

I'm trying to load data from an external .js file, containing a json representation of a bunch of data. I cannot for the life of me figure out how to access the data inside the page. I'm sure this is really easy and I'm missing something simple! right now, I'm trying this:

  $(document).ready(function(){
    $.getJSON("http://api.crunchbase.com/v/1/company/xobni.js",
        function(data){
            alert(data.company_url);
        });
  });

...which is obviously very wrong, since nothing happens. I've tried loading it in a <script> tag, but firebug tells me it didn't even load. how could I screw that up? anyway, I'm about ready to pull my hair out, and I figure this will take someone else about 15 seconds to figure out.

+1  A: 

Looks okay at first glance. Are you sure that the response is valid JSON? Is the content-type incorrect, perhaps? Is the source URL on the exact same domain as your page? (including protocol and port number)

edit:

I loaded your JSON, and there's no "company_url" property.

Tim Sylvester
+4  A: 

that data file doesn't have company_url entry. Additionally, the .js file is served with text/javascript mime-type, when it should be served with application/json (or application/x-javascript, correct me on that).

The real reason, of course, is that you need to add ?callback=? to your url. Then everything is going to work. So, it'll look like this:

$(document).ready(function(){
    $.getJSON("http://api.crunchbase.com/v/1/company/xobni.js?callback=?",
        function(data){
            alert(data.homepage_url);
        });
  });
SilentGhost
i mistyped the variable earlier, that wasn't the code i was actually running :-) the callback fixed it - i'm not really sure what that means or does, but i CAN access the data now! THANK YOU!!
Carly, it probably means that your data and the javascript retrieving it are not on the same domain. Adding the callback param tells jQuery to use JSONP rather than JSON. JSONP is basically a hack to work around cross-domain issues.
Prestaul
+3  A: 

I looked at the json data. It looks like there is no company_url. You might want homepage_url

$(document).ready(function(){
   $.getJSON("http://api.crunchbase.com/v/1/company/xobni.js",
      function(data){
             alert(data.homepage_url);
         });
   });
David Raznick
`data.company_url` would produce undefined if the callback function would run at all.
SilentGhost