javascript Javascript跨域 - “允许”其他域?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5351236/
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
Javascript cross domain - "allow" other domains?
提问by LiverpoolsNumber9
Description of steps
步骤说明
- Write "callback" function on my custom page in my domain (called "MyCallbackCallback", for the sake of argument)
- Open new window (from different domain) and pass function name in as part of query string
- New window does what it needs to do then tries to access "MyCallback" from my custom page
- 在我的域中的自定义页面上编写“回调”函数(为了参数起见,称为“MyCallbackCallback”)
- 打开新窗口(来自不同域)并将函数名称作为查询字符串的一部分传入
- 新窗口执行它需要执行的操作,然后尝试从我的自定义页面访问“MyCallback”
This obviously won'twork and will return "Access denied" error.
这显然不会工作,将返回“拒绝访问”错误。
If there was a way of "allowing" the 3rd-party domain access to my domain that would solve the issue, of course. Is there such a thing? I know there is in Action Script, but JavaScript??
当然,如果有一种“允许”第 3 方域访问我的域的方法可以解决问题。有这样的事情吗?我知道 Action Script 中有,但是 JavaScript 呢??
NB - I am aware that setting "document.domain" on both pages, (or creating both pages in the same domain) will solve the issue, but I almost certainly won'thave this option.
注意 - 我知道在两个页面上设置“document.domain”(或在同一个域中创建两个页面)将解决这个问题,但我几乎肯定不会有这个选项。
If the answer is "you can't" that's fine - I just need to know. I have spent many hours searching and can't find a simple answer (there may not be one!)
如果答案是“你不能”,那很好——我只需要知道。我花了很多时间搜索,但找不到一个简单的答案(可能没有!)
Ta, Rob
塔罗
回答by Mathias Bynens
It's not exactly clear from your question, but if you're trying to use CORS, the server you're requesting data from should add an Access-Control-Allow-Origin
HTTP header, like so:
您的问题并不完全清楚,但是如果您尝试使用CORS,则您从中请求数据的服务器应该添加一个Access-Control-Allow-Origin
HTTP 标头,如下所示:
Access-Control-Allow-Origin: http://example.org/
Or, if it's a public resource:
或者,如果它是公共资源:
Access-Control-Allow-Origin: *
Older browsers don't support CORS. If you need a fully cross-browser-compatible solution, use JSONP.
较旧的浏览器不支持 CORS。如果您需要完全跨浏览器兼容的解决方案,请使用JSONP。
回答by ThiefMaster
Have a look at Cross-Domain AJAX requests:
看看跨域 AJAX 请求:
- https://developer.mozilla.org/En/HTTP_Access_Control
- http://msdn.microsoft.com/en-us/library/dd573303%28v=vs.85%29.aspx
- https://developer.mozilla.org/En/HTTP_Access_Control
- http://msdn.microsoft.com/en-us/library/dd573303%28v=vs.85%29.aspx
JSONPis the only method compatible with older browsers though.
JSONP是唯一与旧浏览器兼容的方法。
回答by Sean Kinsey
If you want cross-domain communication without serverside proxies (perfect for the kind of RPC that you are describing) then take a look at easyXDM.
如果您想要没有服务器端代理的跨域通信(非常适合您所描述的 RPC 类型),请查看easyXDM。
You can find multiple demos here.