JSONP 和 Backbone.js [英] JSONP and Backbone.js
问题描述
我想将 Backbone.js 与我控制的 REST api 一起使用.我希望 REST api 和 Backbone 脚本位于不同的域中,但不幸的是这将被阻止,因为它是跨域请求.
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.
Backbone.js 是否具有支持 JSONP 请求的内置功能?或者,有没有人有将 JSONP 支持手动添加到 Backbone.js sync
系统的经验?
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?
推荐答案
您将无法将整个 REST API 与 JSONP 一起使用.您只能使用 JSONP 调用 GET 请求(它的工作原理是在当前文档上编写一个新的 标签,然后调用 javascript 回调......).
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...).
要使用所有 HTTP 动词(POST、DELETE、PUT),您可以使用 CORS 协议:http://www.w3.org/TR/access-control/.
To use all HTTP verb (POST, DELETE, PUT), you can use the CORS protocol : http://www.w3.org/TR/access-control/.
CORS 是浏览器和 Web 服务之间协商的协议,它告诉浏览器可以通过跨域调用执行 Javascript 代码
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
要使用它,您只需要在服务器响应中包含一些自定义标头,告诉浏览器可以接受跨域请求.这是一篇博客文章,解释了如何使用 RubyOnRails 实现它(但它应该与其他框架非常相似......):http://www.tsheffler.com/blog/?p=428
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
这是最简单的解决方案,您可以像在同一个域中一样使用backbone.js,并且它适用于大多数当前浏览器(Internet Explorer 8+、Firefox 3.5+、Safari 4+ 和 Chrome)!
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) !
如果您需要旧版浏览器支持,我确实设法使用 easyXDM 使主干工作:
If you need older browser support, I did manage to make backbone work using easyXDM :
easyXDM 是一个 Javascript 库,让您作为开发人员可以轻松解决同源策略设置的限制,从而轻松地跨域边界进行通信和公开 javascript API.
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.
它有点复杂,并且可以与一些众所周知的 iframe hacks 一起使用(有时用于 GMaps、facebook 小部件等 javascript 小部件中......).
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, ...).
希望对您有所帮助!
这篇关于JSONP 和 Backbone.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!