这有点小技巧,但你是客户端所以 :)
这段代码做了一些假设——比如myscript.js 的脚本标签存在
假设您的页面上有一些标记,如下所示:\
<script src='../js/myscript.js' type="text/javascript"></script>
<div>hiya</div>
好的,现在我们将使用脚本标签并从中获取基本 url :)
让我们创建一个我们可以使用的 Util 类,添加一个 get base url 方法并提醒该值:
这里的工作副本:http://jsfiddle.net/SmCLy/
function Util() { /*...Nothing...*/
}
Util.getBaseURL = function() {
//<summary>
// Returns the application base URL (well, a URL that is
// equivalent to such - it may have some "backtracking",
// i.e. "../" at
// the end of the URL to simulate the root...)
//</summary>
// 1) Find the script include for this JavaScript file:
var scriptElements = document.getElementsByTagName("script"),
getScriptPathFragmentPosition = Util.getBaseURL._getScriptPathFragmentPosition,
getScriptPathFragmentPositionResult = getScriptPathFragmentPosition(scriptElements, "js/myscript.js"),
posScriptPathFragment = getScriptPathFragmentPositionResult.posScriptPathFragment;
// 2) Create the "base" URL by taking the current URL,
// stripping the page from the end, and appending
// sufficient "../" sequences to
// construct the equivalent of the application's root URL:
var scriptElementSrcLower = getScriptPathFragmentPositionResult.scriptElementSrcLower;
var backPathToRoot = ((scriptElementSrcLower !== "") ? scriptElementSrcLower.substring(0, posScriptPathFragment) : "");
var currentPath = location.href;
var currentPathWithoutPage;
var PAGE_TOKEN = ".aspx";
var posPageToken = currentPath.toLowerCase().indexOf(PAGE_TOKEN);
if (posPageToken > -1) {
var trimmedPath = currentPath.substring(0, posPageToken + PAGE_TOKEN.length);
currentPathWithoutPage = trimmedPath.substring(0, trimmedPath.lastIndexOf("/") + 1);
} else {
currentPathWithoutPage = currentPath.substring(0, currentPath.lastIndexOf("/") + 1);
}
return (currentPathWithoutPage + backPathToRoot);
};
Util.getBaseURL._getScriptPathFragmentPosition = function(scriptElements, scriptPathFragment) {
var scriptElementsIndex = (scriptElements.length - 1),
scriptElementSrc = "",
scriptElementSrcLower = "",
posScriptPathFragment = -1;
while (scriptElementsIndex >= 0) {
scriptElementSrc = scriptElements[scriptElementsIndex].getAttribute("src");
if (typeof(scriptElementSrc) != "undefined" && scriptElementSrc !== null && scriptElementSrc !== "") {
scriptElementSrcLower = scriptElementSrc.toLowerCase();
posScriptPathFragment = scriptElementSrcLower.indexOf(scriptPathFragment);
if (posScriptPathFragment >= 0) {
break;
}
}
scriptElementsIndex--;
}
var result = {
posScriptPathFragment: posScriptPathFragment,
scriptElementSrcLower: scriptElementSrcLower
};
return result;
};
alert(Util.getBaseURL());
所以,在你的页面上你可以这样做:
var myajaxUrl = getBaseURL()+"MyPage/GetDetails";