問題描述
如果我的用戶在我自己的網頁上,我知道:http://www.example.com/form.php
I know if on my own webpage, if my user is on :
http://www.example.com/form.php
然后我從該頁面發出 ajax 請求:http://example.com/responder.php
and I make an ajax request from that page to :
http://example.com/responder.php
由于同源策略(子域不同),它將失敗.
It will fail because of the Same origin policy (subdomain is different).
我想了解的是,當請求和服務器明顯不同時,AJAX 請求如何從 flickr 等 API 中提取數據.
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.
eg:為什么這段代碼有效?
Edit :
eg: Why does this code work?
$.getJSON('http://api.flickr.com/services/rest/?&;method=flickr...'
(參考了這個社區維基)是否使用跨源資源共享?
謝謝!
推薦答案
解決同源策略的已知方法很少.一種流行的技術是使用腳本標簽注入",例如 JSONP.由于 <script>
標簽不受同源策略的約束,第三方域上的腳本可以提供與提供的回調函數交互的可執行代碼.您可能需要查看以下文章中的提示和技巧"部分以進一步閱讀該主題:
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:
- 如何動態插入 Javascript 和 CSS (hunlock.com)
- Howto Dynamically Insert Javascript And CSS (hunlock.com)
您可能也有興趣查看以下 Stack Overflow 帖子,以進一步閱讀解決同源策略的其他技術:
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:
- 規避同源策略的方法
更新:進一步更新問題:
引用 $.getJSON()
上的 jQuery 文檔一個>:
Quoting from the jQuery documentation on $.getJSON()
:
如果 URL 包含字符串callback=?"在 URL 中,請求被視為 JSONP.
If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead.
這篇關于同源策略 - AJAX &使用公共 API的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!