I run a REST-API build on top of Sinatra. Now I want to write a jQuery Script that fetches data from the API.
Sinatra is told to response with JSON
befor
Use JSONP (JSON with padding). There is a JSONP extension for Rack.
Basically, you'll call:
$.ajax({
type: 'get',
url: 'http://api.com/posts',
dataType: 'jsonp',
success: function(data) {
// do something
}
})
which translates to a request like:
http://api.com/posts?callback=someJSFunc
and your server will respond, e.g.:
someJSFunc({"json":"obj"});
Of course, clients can do JSONP requests without jQuery. The trick with JSONP is you serve scripts, which can be cross-domain, rather than pure JSON, with cannot.