让javascript使用它所在的目录

Luk*_*uke 2 html javascript

我在名为test的文件夹中有一个名为foo.js的小脚本,其中目录的位置未知:

$.post("bar.php");
Run Code Online (Sandbox Code Playgroud)

它由两个不同的html文件使用,一个在/test/index.html:

<script src="foo.js"></script>
Run Code Online (Sandbox Code Playgroud)

另一个在/test/index.html:

<script src="../foo.js"></script>
Run Code Online (Sandbox Code Playgroud)

当我从/index.html运行脚本时,它工作正常,并调用bar.php.但是当我从/subdirectory/index.html调用它时,javascript告诉我无法找到资源(bar.php).但是,如果我将bar.php复制并粘贴到/子目录中,则可以正常工作.

有没有办法让javascript使用脚本所在的目录(在本例中为test),而不是使用最初调用的目录?

Pau*_*aul 5

使用相对于您的域的路径,方法是/:

$.post("/bar.php");
Run Code Online (Sandbox Code Playgroud)

这样,无论脚本在哪里,或者调用它的HTML文件在哪里,都只是重要的位置bar.php.您也应该包括foo.js相同的方式:

<script src="/foo.js"></script>
Run Code Online (Sandbox Code Playgroud)

这将适用于两个文件/index.html和/subdirectory/index.html.

编辑:要实际找到脚本所在的位置(相对于当前页面),您可以使用:

(function(){
  var myDirectory = (function(){
    var script = document.currentScript || // SHIM
      (function(){
        var scripts = document.getElementsByTagName('script');
        return scripts[scripts.length - 1];
      })();

    var src = script.getAttribute('src');
    return src.substr(0, src.lastIndexOf('/')) + '/';
  })();


  // The rest of your script here, then, wherever you make the post request:
       $.post(myDirectory + "bar.php");

})();
Run Code Online (Sandbox Code Playgroud)