19

同源策略如何适用于以下两个域?

http://server1.MyDomain.com

http://server2.MyDomain.com

如果内容是从 server2 检索的,我可以在 server1 上托管的页面上运行 JS 吗?

根据下面丹尼尔的回答进行编辑<script>,我可以使用标签在不同子域之间包含脚本,但是异步请求呢?如果我从 server2 下载脚本到 server1 上托管的页面会怎样。我可以使用脚本与 server2 上的服务进行异步通信吗?

4

2 回答 2

24

您只能使用<script>标签在不同子域之间包含脚本,因为它不受策略约束。

用作http://www.example.com/dir/page.html来源(来自维基百科):

Compared URL                               Outcome  Reason
---------------------------------------------------------------------------------------------
http://www.example.com/dir/page.html       Success  Same protocol and host
http://www.example.com/dir2/other.html     Success  Same protocol and host
http://www.example.com:81/dir2/other.html  Failure  Same protocol and host but different port
https://www.example.com/dir2/other.html    Failure  Different protocol
http://en.example.com/dir2/other.html      Failure  Different host
http://example.com/dir2/other.html         Failure  Different host (exact match required)
http://v2.www.example.com/dir2/other.html  Failure  Different host (exact match required)

更新:

我可以使用脚本与 server2 上的服务进行异步通信吗?

是的,您可以使用JSONP,它利用<script>标签的开放策略从其他来源检索 JSON。

您可能还需要考虑使用反向代理,如以下 Stack Overflow 帖子所述:

于 2010-03-30T08:35:35.530 回答
0

当然,你可以运行你插入的任何脚本,不管它来自哪里。考虑如何在您的页面上插入谷歌地图。

您描述的是一种称为 jsonp 的模式。其他主机上的服务器返回您在页面中插入的脚本,并且该脚本使用响应参数调用页面中的函数。

于 2010-03-30T08:48:23.733 回答