Sinatra,JavaScript跨域请求JSON

问题描述:

我在Sinatra上运行REST-API构建。
现在我想写一个jQuery Script从API中获取数据。

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被告知要用JSON响应

Sinatra is told to response with JSON

before do
  content_type :json
end

一个简单的Route看起来像

A simple Route looks like

get '/posts' do
  Post.find.to_json
end

我的jQuery脚本是一个简单的ajax调用

My jQuery script is a simple ajax-call

$.ajax({
  type: 'get',
  url: 'http://api.com/posts',
  dataType: 'json',
  success: function(data) {
     // do something
  }
})

实际上一切正常,只要两个运行在相同的IP,API和请求JS。
我已经尝试使用JSONP的Rack没有任何积极的结果,但。

Actually everything works fine as long as both runs on the same IP, API and requesting JS. I already tried to play around with JSONP for Rack without any positive results, though. Probably I just need a hint how to proceed.

使用 JSONP (带填充的JSON)。有 JSONP扩展用于Rack。

Use JSONP (JSON with padding). There is a JSONP extension for Rack.

基本上,你会调用:

$.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"});

当然,客户端可以在没有jQuery的情况下执行JSONP请求。 JSONP的技巧是你提供脚本,它可以是跨域的,而不是纯JSON,不能。

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.