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?
Use
callback=?instead, like this: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 thatsuccessfunction 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:
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 🙂