【发布时间】:2014-12-11 21:59:48
【问题描述】:
我使用 Ajax 下载 HTML 代码,然后解析它:
var req = new XMLHttpRequest();
//Request for the current URL (such as http://example.org or http://stackoverflow.com/questions/27433215/give-document-proper-url-or-location)
req.open("GET", window.location.href);
req.onload = function() {
//Returns Document object with `about:blank` in URL
var doc = document.implementation.createHTMLDocument();
//Put the code from request to the Document (all relative URL's are now lost)
doc.documentElement.innerHTML = this.responseText;
window.loadedDoc = doc;
}
req.send();
问题在于文档的 URL 是about:blank。这会导致任何相对 URL 导致错误的路径。最重要的是,从<a> 中选择href 会得到/path/ 而不是http://example.com/path/。
我可以在某些时候设置正确的Document.URL 吗? url 应该与当前的window.location 相同 - 所以没有安全风险!
如果浏览器实现没有处理这种情况,是否至少可以正确替换链接 URL?
【问题讨论】:
-
问题是,为什么位置是
about:blank,你为什么要从那里做ajax请求,到什么地方,你如何避免同源策略? -
@adeneo CORS 何时适用于
window.location.href?请检查代码。 -
不会吧,Cross Origin Resource Sharing大概跟这个没什么关系,但是我根本没提过CORS?
-
CORS 是同源策略的子集。你指的是哪一部分?我似乎违反了它的哪一部分以及如何违反?我真的只是通过 Ajax 加载当前 URL。我需要一个具有相同 URL 的文档。
-
你将如何执行跨域 AJAX 请求?他们是被禁止的。
标签: javascript html domdocument