对文件发出 json/jsonp xhr 请求:协议
我正在编写一个 javascript 应用程序,它将托管在 file:
协议上(即:该应用程序只是位于我硬盘驱动器上某个位置的 html、css 和 javascript 的文件夹)。当我尝试正常的 XHR 请求时,它们由于同源策略问题而失败。
所以我的问题是,如上所述,使用应用程序请求 json/jsonp 文件的最佳方式是什么?
注意:到目前为止,我已经使用硬编码回调函数获得了所有 jsonp 文件,但我希望能够对这些请求使用动态回调函数。有没有办法做到这一点?
I'm writing a javascript app that will be hosted on a file:
protocol (ie: the application is just a folder of html, css, and javascript sitting someplace on my hard drive). When I try normal XHR requests they fail because of the same origin policy afaict.
So my question is this, what's the best way to request json/jsonp files with an app as described above?
Note: So far I've got all of my jsonp files using a hard-coded callback functions, but I'd like to be able to use dynamic callback functions for these requests.. is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种棘手的工作,但它会给你带来动态回调。基本上,它依赖于
file:
传输速度相当快的事实。它建立一个请求队列并一次发送一个请求。这是我能找到的确保可以链接正确的响应和回调(以保证的顺序)的唯一方法。希望有人能想出更好的方法,但在无法动态生成响应的情况下,这是我能做的最好的事情。};
这就是我测试
Data.js所做的
This is kind of a hatchet job, but it will get you your dynamic callbacks. Basically it counts on the fact that
file:
transfers will be pretty fast. It sets up a queue of requests and sends them out one at a time. That was the only way I could figure out to make sure that the correct response and callback could be linked (in a guaranteed order). Hopefully someone can come up with a better way, but without being able to dynamically generate the responses, this is the best I can do.};
This is what I did to test
Data.js
出于安全原因,Chrome 对从 file:// url 进行 ajax 调用有非常严格的限制。他们知道这会破坏本地运行的应用程序,并且
Ajax 在 Firefox 中可以很好地处理文件 url,只需注意返回代码不是 http 状态代码;即,0 表示成功,而不是 200-299 + 304。IE
处理这些安全问题的方式与 Chrome 和 Firefox 不同,我希望其他浏览器都有自己的方法。 Web 和桌面应用程序之间的边界是一个非常有问题的领域。
Chrome has very tight restrictions on making ajax calls from a file:// url, for security reasons. They know it breaks apps that run locally, and there's been a lot of debate about alternatives, but that's how it stands today.
Ajax works fine from file urls in Firefox, just be aware that the return code is not an http status code; i.e., 0 is success, not 200-299 + 304.
IE handles these security concerns differently from both Chrome and Firefox, and I'd expect other browsers to each have their own approaches. The border between web and desktop apps is very problematic territory.