gpt4 book ai didi

从父域到子域的 JavaScript 访问?

转载 作者:可可西里 更新时间:2023-11-01 01:25:42 24 4
gpt4 key购买 nike

我读过设置 document.domain = "example.com" 允许我从子域访问父域。

反之亦然吗?

假设我的主站点在 http://example.com 下运行。我想通过 AJAX(GET 和 POST)访问的所有 API 函数都托管在 http://api.example.com 上。

我可以从 example.com 访问 api.example.com 吗?

编辑:再次查看document.domain,我认为这不会解决问题。调用 api.example.com 的结果不是必需的 HTML,而是 API 服务器上运行的 PHP 脚本的输出。它可以是 JSON、纯文本等。因此无法为此设置 document.domain(因为它不是 iframe)。

最佳答案

您需要在两个页面上设置 document.domain

或者在您的服务器上设置 CORS header :

http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/

A Quick Overview of CORS

Firefox 3.5 and Safari 4 implement the CORS specification, using XMLHttpRequest as an “API container” that sends and receives the appropriate headers on behalf of the web developer, thus allowing cross-site requests. IE8 implements part of the CORS specification, using XDomainRequest as a similar “API container” for CORS, enabling simple cross-site GET and POST requests. Notably, these browsers send the ORIGIN header, which provides the scheme (http:// or https://) and the domain of the page that is making the cross-site request. Server developers have to ensure that they send the right headers back, notably the Access-Control-Allow-Origin header for the ORIGIN in question (or ” * ” for all domains, if the resource is public) .

The CORS standard works by adding new HTTP headers that allow servers to serve resources to permitted origin domains. Browsers support these headers and enforce the restrictions they establish. Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers “preflight” the request, soliciting supported methods from the server with an HTTP OPTIONS request header, and then, upon “approval” from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether “credentials” (including Cookies and HTTP Authentication data) should be sent with requests.

关于从父域到子域的 JavaScript 访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6277926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com