Sinatra, JavaScript Cross-Domain Requests JSON

折月煮酒 提交于 2019-12-03 00:51:48

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.

Thank's for the answers so far. You were right and jsonp would solve the problem. The code snippets for javascript work fine. To set up Sinatra is very easy as it is build on top of Rack. Therefore simply install the rack-contrib gem

 gem install rack-rack-contrib --source=http://gems.github.com/

(or put it in your Gemfile) and add

require 'rack/contrib/jsonp'
use Rack::JSONP

to your application.

This middleware provides regular JSON to non-JSONP clients and JSONP to jQuery & co.

It might be interesting to you http://github.com/shtirlic/sinatra-jsonp — this extension adds missing functionality to sinatra

Also available as gem gem install sinatra-jsonp

Andrew Bashtannik

Try to call

$.getJSON("http://example.com/?callback=?",function(data) { alert(data); });

In this sample main keyword is construction "callback=?", so you need to process this param in your server-side script, and make a valid JSONP, like this:

function({ "foo" : "bar" });

Where "function" is random data, which is generated by jQuery automatically. Read more here about jQuery and cross-domain JSONP.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!