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?
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/.
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 :
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!