我有一个包含PHP和JavaScript文件的脚本。所有这些文件都在根文件夹/myfolder中。
假设我在我的网站上必须包含的脚本是/myfolder/script.js,问题是在script.js中我有对../myfolder/ajax.php的ajax调用,因为路径是相对于页面的,所以如果我在页面/a/b/page.php上有这样的内容,脚本就不会起作用
<script src="../../myfolder/script.js><script>,因为这将从ajax调用中声明的../myfolder/ajax.php调用AJAX方法,在本例中为/a/myfolder/ajax.php。
如何重写AJAX call URL,使其始终指向正确的文件,而不管script.js位于何处?
ROOT
|---myfolder
|--script.js
|--ajax.php
|--page1.php
|--subfolder
|--page2.php
|--subfolder
|--page3.php发布于 2013-02-05 21:01:47
/**
* 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) ? '' : '/');
}在像http://www.example.com/ajax这样的网址上
getContextPath() + 'myfolder/ajax.php'将返回/ajax/myfolder/ajax.php
类似于像http://www.example.com/这样的URL
getContextPath() + 'myfolder/ajax.php'将返回/myfolder/ajax.php
最后是像http://www.example.com/myfolder/a/b/c/d/e/f/g/这样的网址
getContextPath() + 'myfolder/ajax.php'将返回/myfolder/ajax.php
https://stackoverflow.com/questions/14708003
复制相似问题