XMLHttpRequest.send failing with relative path

僤鯓⒐⒋嵵緔 提交于 2019-12-22 11:13:18

问题


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.

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.

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.

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.

Thank you.

Code Snippet:

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
}

回答1:


From the MDN website, about the Gecko engine and therefore the Firefox browser:

a file can read another file only if the parent directory of the originating file is an ancestor directory of the target 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

From within index.html, you can use Javascript to access file3.html and file4.html. It cannot access file1.html or file2.html.




回答2:


Open the file in your browser directly using file->open then copy the URL in the address bar.



来源:https://stackoverflow.com/questions/20106231/xmlhttprequest-send-failing-with-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!