Chris W.
Chris W.

Reputation: 39219

JSONP and Backbone.js

I would like to use Backbone.js with a REST api I control. I was hoping to have the REST api and the Backbone scripts live on a different domain but unfortunately this will be blocked, as it is a cross domain request.

Does Backbone.js have an built in functionality to support JSONP requests? Or, alternatively, does anyone have any experience with manually adding JSONP support to Backbone.js sync system?

Upvotes: 26

Views: 13176

Answers (2)

Tricote
Tricote

Reputation: 1508

You will not be able to use your entire REST API with JSONP. You can only call GET requests with JSONP (it works by writing a new <script> tag on the current document, then calling a javascript callback...).

To use all HTTP verb (POST, DELETE, PUT), you can use the CORS protocol : http://www.w3.org/TR/access-control/.

CORS is a protocol negotiated between a browser and a web-service that tells the browser that it is “OK” to execute Javascript code from a cross-domain call

To use this, you just need to include some custom headers in your server response that tells the browser that it's ok to accept cross domain requests. Here's an blog post that explains how to implement it with RubyOnRails (but it should be quite similar with others framework...) : http://www.tsheffler.com/blog/?p=428

It's the simplest solution, you can use backbone.js as if you where on the same domain, and it works with most current browsers (Internet Explorer 8+, Firefox 3.5+, Safari 4+, and Chrome) !

If you need older browser support, I did manage to make backbone work using easyXDM :

easyXDM is a Javascript library that enables you as a developer to easily work around the limitation set in place by the Same Origin Policy, in turn making it easy to communicate and expose javascript API's across domain boundaries.

It's a little more complicated, and works with a some well known iframe hacks (that are sometimes used in javascript widgets like GMaps, facebook widgets, ...).

Hope this help!

Upvotes: 20

RandallB
RandallB

Reputation: 5575

JSONP support for GET operations can be added via fetch's options.

In the same hash where you configure your success and error handlers, add an object like so:

{dataType: "jsonp"}

This will pass along the jsonp option to JQuery's ajax handler, and automagically, you'll have JSONP support for retrieving models / collections.

Upvotes: 34

Related Questions