XMLHttpRequest.send失败,带有相对路径 [英] XMLHttpRequest.send failing with relative path
问题描述
我很难找到可能有所补救的东西。我正在开发一个没有服务器的网站。这样做时,我在尝试通过XMLHttpRequest访问文件时遇到了问题。
I'm having difficulty with something probably remedial. I'm developing a website without a server. In doing so, I run into problems when trying to access files via XMLHttpRequest.
正如您在示例代码片段中所看到的,我创建变量,使用相应路径打开它并使用send函数。
As you can see in the example code snippet, I create the variable, open it with a relative path to the desired file, and use the send function.
当我使用必须遍历父目录的相对路径时,send()函数失败。但是,如果我提供的路径与网页位于同一目录中,或者在当前网页目录的子文件夹中转发,我会看到XMLHttpRequest成功返回。在这些成功的案例中,我可以在request.responseText中看到测试文件的数据。
When I use a relative path that has to traverse up to a parent directory, the send() function fails. However, if I provide a path that is either in the same directory as the webpage or forward in a subfolder of the current webpage directory, i see that the XMLHttpRequest returns successfully. In these successful cases, I can see the data of the test file in request.responseText.
对此的任何帮助将不胜感激。
Any help with this would be greatly appreciated.
我现在唯一的领先是可能存在安全威胁,阻止get请求遍历父目录。
The only lead I have right now is that there may be a security threat that prevents 'get' requests that traverse up the parent directory.
谢谢。
代码片段:
function test(){
var request = new XMLHttpRequest();
request.open('GET', "../test.txt", true);
request.send();//FAILS HERE
//Get Response
var response = request.responseText;
}
function test2(){
var request = new XMLHttpRequest();
request.open('GET', "test.txt", true);
request.send();
//Get Response
var response = request.responseText; //SUCCESSFUL
}
推荐答案
来自 MDN网站:
只有当原始文件的父目录是目标文件的祖先目录时,文件才能读取另一个文件。
a file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.
其他浏览器中也存在类似的规则。这是 file:///
协议的限制。这是有充分理由的。试图打破它是没有意义的。解决方案是在您的计算机上运行本地服务器,这甚至有点困难。
Similar rules exist in other browsers. This is a limitation of the file:///
protocol. It's there for a very good reason. There's no point trying to break it. The solution is to run a local server on your computer, which isn't even slightly difficult.
为了澄清:让我们假设您有这样的文件结构:
To clarify: let's presume that you have a file structure like this:
- file1.html
- dir1/
- file2.html
- dir2/
- index.html
- file3.html
- dir3/
- file4.html
在 index.html
中,您可以使用Javascript访问 file3.html
和 file4.html
。它无法访问 file1.html
或 file2.html
。
From within index.html
, you can use Javascript to access file3.html
and file4.html
. It cannot access file1.html
or file2.html
.
这篇关于XMLHttpRequest.send失败,带有相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!