tags:

views:

43

answers:

2

Hello. I am attempting to get some information from a russian shipping website. Being a n00b to JSON/Jquery/Internets I am stuck getting the data into json format.

Following the company's API, I go to the URL: http://emspost.ru/api/rest/?callback=json&method=ems.calculate&from=city--abakan&to=city--anadyr&weight=1

This returns:

json({"rsp":{"stat":"ok","price":"750","term":{"min":5,"max":9}}})

Following Jquery's docs, I have tried:

<script>$.getJSON("http://emspost.ru/api/rest/?callback=json&amp;method=ems.calculate&amp;from=city--abakan&amp;to=city--anadyr&amp;weight=1",
        function(data){
        alert(data);
        });</script>

This returns null. Any idea what I'm doing wrong?

A: 

You are using a callback function (callback=json) which runs the function json when it loads.

Try GETting this instead:

http://emspost.ru/api/rest/?method=ems.calculate&amp;from=city--abakan&amp;to=city--anadyr&amp;weight=1

Btw, is your request crossdomain? If so, an xhr is not suggested.

digitalFresh
+4  A: 

Use callback=? instead, like this:

$.getJSON("http://emspost.ru/api/rest/?callback=?&amp;method=ems.calculate&amp;from=city--abakan&amp;to=city--anadyr&amp;weight=1",
function(data){
  alert(data);
});

Then you'll get your object in the alert :) JSONP works by taking that callback in the querystring and calling that function (which doesn't exist, unless you made a function json() {} when it returns. When you do ?callback=? jquery dynamically names that success function you gave to $.getJSON() and replaces it, like this: ?callback=FunctioNameGiven, so it'll actually run correctly.

If you think about how it runs, it's basically:

<script type="text/javascript">
  //returned javascript here, e.g. FunctioNameGiven({ object data });
</script>

This is done so it's a GET request, and not limited by same-origin policy rules, that's how JSONP works where a normal JSON request gets blocked :)

Nick Craver
I'd like to add that the '?' mark is required to trigger JSONP support in jQuery... if it's omitted, jQuery won't know it's JSONP and will try to fetch the data as if it were a normal JSON requests, which will not work.
chakrit
@chakrit - Good point, I'd add a caveat though, this is true for `$.getJSON()`, but not jQuery overall (though it's the easiest route), for example: http://jsfiddle.net/jF6yj/
Nick Craver