同源策略 - AJAX &使用公共 API

如果我的用户在我自己的网页上,我知道: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.

相关文章