javascript 同源策略 - AJAX 和使用公共 API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3536800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Same Origin Policy - AJAX & using Public APIs
提问by DMin
I know if on my own webpage, if my user is on :
http://www.example.com/form.php
我知道是否在我自己的网页上,如果我的用户在:http:
//www.example.com/form.php
and I make an ajax request from that page to :
http://example.com/responder.php
我从那个页面向 ajax 请求:http:
//example.com/responder.php
It will fail because of the Same origin policy (subdomain is different).
由于同源策略(子域不同),它将失败。
What I am trying to understand is, how is it that AJAX requests can pull data from API's like flickr when the request and server are obviously different.
我想理解的是,当请求和服务器明显不同时,AJAX 请求如何从像 flickr 这样的 API 中提取数据。
Edit :
eg: Why does this code work?
编辑:
例如:为什么这段代码有效?
$.getJSON('http://api.flickr.com/services/rest/?&;method=flickr...'
(Referred this Community Wiki) Is it using Cross Origin Resource Sharing?
Thanks!
谢谢!
采纳答案by Daniel Vassallo
There are few known methods to work around the Same Origin Policy. One popular technique is to use "Script Tag Injection" such as in JSONP. Since the <script>tag is not constrained by the Same Origin Policy, a script on a third-party domain can provide executable code that interacts with a provided callback function. You may want to check out the "Tips and Tricks" section in the following article for further reading on the topic:
解决同源策略的已知方法很少。一种流行的技术是使用“脚本标签注入”,例如在JSONP 中。由于<script>标签不受同源策略的约束,第三方域上的脚本可以提供与提供的回调函数交互的可执行代码。您可能需要查看以下文章中的“提示和技巧”部分以进一步阅读该主题:
- Howto Dynamically Insert Javascript And CSS(hunlock.com)
- 如何动态插入 Javascript 和 CSS(hunlock.com)
You may also be interested in checking out the following Stack Overflow post for further reading on other techniques to work around the Same Origin Policy:
您可能也有兴趣查看以下 Stack Overflow 帖子,以进一步阅读其他技术来解决同源策略:
UPDATE:Further the updated question:
更新:进一步更新的问题:
Quoting from the jQuery documentation on $.getJSON():
引用 jQuery 文档$.getJSON():
If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead.
如果 URL 包含字符串“callback=?” 在 URL 中,请求被视为 JSONP。

