I want to work with backbone.js and jquery. The app is supposed to run offline on mobile phones (i.e. "localhost"), there are few calls on a server side backend somewhere in the internet.
What is the best way to realize cross domain requests with backbone.js?
I would like to use JSON, but I could eventually switch back to REST if necessary.
Here's my not very impressive code so far:
App.Collections.Events = Backbone.Collection.extend({
model: Event,
url: 'http://mydomain.com/api/getevents/user_id/1/'
});
BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
Backbone is an open-source component of DocumentCloud.
There are two ways of allowing cross-domain XMLHttpRequests, which is the method Backbone.js uses to fetch data from a URL. The first is appropriate if you've got control of the server-side of the non-origin domain you're trying to connect to, and involves implenting Cross-Origin Resource Sharing (or CORS).
To implement CORS, return the 'Origin' part the HTTP Referer
request header (the bit up to the beginning of the path
; it should match regex ^.+?\/{2}[^\/]*
) in the Access-Control-Allow-Origin
response header for domains you want to serve to:
Access-Control-Allow-Origin: http://mydomain.com
You might need to override Backbone.sync in order for the right settings to be set on the XMLHttpRequest object.
The second option, if you don't have access to the cross-origin server, would be to proxy the requests through your own server (either the origin one or one which enables CORS). Obviously whoever owns the domain you're trying to call mightn't like you doing that, but that is by design - if they don't want you calling your service, they only have one IP address to block, instead of each of your clients' IP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With