Sinatra, JavaScript Cross-Domain Requests JSON

后端 未结 4 1485
眼角桃花
眼角桃花 2021-02-06 19:58

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         


        
4条回答
  •  感情败类
    2021-02-06 20:29

    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.

提交回复
热议问题