Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this valid JSON markup?

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&method=ems.calculate&from=city--abakan&to=city--anadyr&weight=1",
  function(data) {
    alert(data);
  });
</script>

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

like image 414
jdkealy Avatar asked May 11 '26 01:05

jdkealy


2 Answers

Use callback=? instead, like this:

$.getJSON("http://emspost.ru/api/rest/?callback=?&method=ems.calculate&from=city--abakan&to=city--anadyr&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 :)

like image 176
Nick Craver Avatar answered May 13 '26 15:05

Nick Craver


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&from=city--abakan&to=city--anadyr&weight=1

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

like image 22
tcooc Avatar answered May 13 '26 15:05

tcooc