3

我有一个包含 PHP 和 JavaScript 文件的脚本。所有这些文件都在根文件夹/myfolder中。

假设我必须在我的网站上包含的脚本是/myfolder/script.js,问题是script.js我有 ajax 调用../myfolder/ajax.php,因为路径将相对于包含脚本的页面,如果我有类似这样的内容将不起作用页面/a/b/page.php

<script src="../../myfolder/script.js><script>因为这将../myfolder/ajax.php按照 AJAX 调用中的说明调用 ajax 方法,在本例中为/a/myfolder/ajax.php.

如何重写 AJAX 调用 URL,使其始终指向正确的文件,无论script.js它包含在何处?

ROOT
|---myfolder
    |--script.js
    |--ajax.php
|--page1.php
|--subfolder
   |--page2.php
   |--subfolder
      |--page3.php
4

1 回答 1

7
/**
 * returns the current context path,
 * ex: http://localhost:8080/MyApp/Controller returns /MyApp/
 * ex: http://localhost:8080/MyApp returns /MyApp/
 * ex: https://www.example.co.za/ returns /
 */
function getContextPath() {
    var ctx = window.location.pathname,
        path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx;
    return path + (/\/$/.test(path) ? '' : '/');
}

在这样的 URL 上http://www.example.com/ajax

getContextPath() + 'myfolder/ajax.php'

将返回/ajax/myfolder/ajax.php


类似地在如下 URL 上http://www.example.com/

getContextPath() + 'myfolder/ajax.php'

将返回/myfolder/ajax.php


最后在一个 URL 上,例如http://www.example.com/myfolder/a/b/c/d/e/f/g/

getContextPath() + 'myfolder/ajax.php'

将返回/myfolder/ajax.php

于 2013-02-05T13:01:46.820 回答