2

I have a small script called foo.js in a folder called test where the location of the directory is unknown:

$.post("bar.php");

It's used by two different html files, one at /test/index.html:

<script src="foo.js"></script>

The other at /test/index.html:

<script src="../foo.js"></script>

When I run the script from /index.html, it works fine and bar.php is called. But when I call it from /subdirectory/index.html, javascript tells me that the resource (bar.php) can't be found. However if I copy and paste bar.php into /subdirectory, it works.

Is there a way to have javascript use the directory the script is located at (in this case, test), instead of using whatever directory it was originally called from?

4

2 回答 2

5

使用相对于您的域的路径,通过以下方式开始/

$.post("/bar.php");

这样,脚本在哪里或调用它的 HTML 文件在哪里都无关紧要,重要的是它的位置bar.php。您可能还应该包括foo.js相同的方式:

<script src="/foo.js"></script>

这将在文件/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");

})();
于 2013-08-28T21:17:15.450 回答
2

尝试/bar.php

您需要使用相对路径

于 2013-08-28T21:17:52.377 回答